]> git.lyx.org Git - lyx.git/blob - src/mathed/formula.C
a90787fba9d61658a8e860b0908d04590488344b
[lyx.git] / src / mathed / formula.C
1 /*
2  *  File:        formula.h
3  *  Purpose:     Implementation of formula inset
4  *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx> 
5  *  Created:     January 1996
6  *  Description: Allows the edition of math paragraphs inside Lyx. 
7  *
8  *  Copyright: (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 "lyx_cb.h"
31 #include "minibuffer.h"
32 #include "BufferView.h"
33 #include "lyxtext.h"
34 #include "gettext.h"
35 #include "LaTeXFeatures.h"
36 #include "debug.h"
37 #include "lyx_gui_misc.h"
38 #include "support/LOstream.h"
39 #include "LyXView.h"
40 #include "Painter.h"
41
42 extern void UpdateInset(BufferView *, Inset * inset, bool mark_dirty = true);
43
44 extern char * mathed_label;
45
46 extern char const * latex_special_chars;
47
48 short greek_kb_flag = 0;
49
50 LyXFont * Math_Fonts = 0; // this is only used by Whichfont and mathed_init_fonts (Lgb)
51
52 static LyXFont::FONT_SIZE lfont_size = LyXFont::SIZE_NORMAL;
53
54 // local global 
55 static int sel_x, sel_y;
56 static bool sel_flag;
57 MathedCursor * InsetFormula::mathcursor = 0; 
58
59
60 int MathedInset::df_asc;
61 int MathedInset::df_des;
62 int MathedInset::df_width;
63
64
65 inline bool IsMacro(short token, int id)
66 {
67    return (token != LM_TK_FRAC && token != LM_TK_SQRT &&
68           !((token == LM_TK_SYM || token == LM_TC_BSYM) && id < 255));
69 }
70
71
72 static
73 void mathedValidate(LaTeXFeatures & features, MathParInset * par);
74
75
76 LyXFont WhichFont(short type, int size)
77 {
78     LyXFont f;
79     
80       if (!Math_Fonts)
81         mathed_init_fonts();
82    
83    switch (type) {
84     case LM_TC_SYMB:         
85       f = Math_Fonts[2];
86       break;
87     case LM_TC_BSYM:         
88       f = Math_Fonts[2];
89       break;
90     case LM_TC_VAR:
91     case LM_TC_IT:
92       f = Math_Fonts[0];
93       break;
94     case LM_TC_BF:
95       f = Math_Fonts[3];
96       break;
97     case LM_TC_SF:
98       f = Math_Fonts[7];
99       break;
100     case LM_TC_CAL:
101       f = Math_Fonts[4];
102       break;
103     case LM_TC_TT:
104       f = Math_Fonts[5];
105       break;
106     case LM_TC_SPECIAL: //f = Math_Fonts[0]; break;
107     case LM_TC_TEXTRM:
108     case LM_TC_RM:    
109       f = Math_Fonts[6];
110       break;
111     default:
112       f = Math_Fonts[1];
113       break;   
114    }
115     
116     f.setSize(lfont_size);
117     
118     switch (size) {
119      case LM_ST_DISPLAY:     
120         if (type == LM_TC_BSYM) {
121             f.incSize();
122             f.incSize();
123         }
124         break;
125      case LM_ST_TEXT:
126         break;
127      case LM_ST_SCRIPT:
128         f.decSize();
129         break;
130      case LM_ST_SCRIPTSCRIPT:
131         f.decSize();
132         f.decSize();
133         break;
134      default:
135              lyxerr << "Mathed Error: wrong font size: " << size << endl;
136         break;
137     }
138
139     if (type != LM_TC_TEXTRM) 
140       f.setColor(LColor::math);
141     return f;
142 }
143
144
145 void mathed_init_fonts() //removed 'static' because DEC cxx does not
146                          //like it (JMarc)
147         // Probably because this func is declared as a friend in math_defs.h
148         // Lgb
149 {
150
151     Math_Fonts = new LyXFont[8]; //DEC cxx cannot initialize all fonts
152                                  //at once (JMarc) rc
153     for (int i = 0 ; i < 8 ; ++i){ 
154         Math_Fonts[i] = LyXFont(LyXFont::ALL_SANE);
155     }
156     Math_Fonts[0].setShape(LyXFont::ITALIC_SHAPE);
157     
158     Math_Fonts[1].setFamily(LyXFont::SYMBOL_FAMILY);
159     
160     Math_Fonts[2].setFamily(LyXFont::SYMBOL_FAMILY);
161     Math_Fonts[2].setShape(LyXFont::ITALIC_SHAPE);
162
163     Math_Fonts[3].setSeries(LyXFont::BOLD_SERIES);
164       
165     Math_Fonts[4].setFamily(LyXFont::SANS_FAMILY);
166     Math_Fonts[4].setShape(LyXFont::ITALIC_SHAPE);
167       
168     Math_Fonts[5].setFamily(LyXFont::TYPEWRITER_FAMILY);
169
170     Math_Fonts[6].setFamily(LyXFont::ROMAN_FAMILY);
171
172     Math_Fonts[7].setFamily(LyXFont::SANS_FAMILY);
173     
174     LyXFont f = WhichFont(LM_TC_VAR, LM_ST_TEXT);
175     MathedInset::df_asc = f.maxAscent(); 
176     MathedInset::df_des = f.maxDescent();
177     MathedInset::df_width = f.width('I');    
178 }
179
180
181 LyXFont mathed_get_font(short type, int size)
182 {
183         LyXFont f = WhichFont(type, size);
184         if (type == LM_TC_TEX) {
185                 f.setLatex(LyXFont::ON);
186         }
187         return f;
188 }
189
190
191 int mathed_string_width(short type, int size, byte const * s, int ls)
192 {
193     LyXFont f = WhichFont(type, size);
194
195     byte sx[80];
196     if (MathIsBinary(type)) {
197         byte * ps = &sx[0];
198         for (int i = 0; i < ls && i < 75; ++i) {
199             *(ps++) = ' ';
200             *(ps++) = s[i];
201             *(ps++) = ' ';
202         }
203         *(ps++) = '\0';
204         ls *= 3;
205         s = &sx[0];
206     }
207     return f.textWidth(reinterpret_cast<char const *>(s), ls);
208 }
209
210
211 int mathed_char_width(short type, int size, byte c)
212 {
213     int t = (MathIsBinary(type)) ? mathed_string_width(type, size, &c, 1):
214            WhichFont(type, size).width(c);
215     return t;
216 }
217
218
219 int mathed_string_height(short type, int size, byte const * s,
220                          int ls, int & asc, int & des)
221 {
222    LyXFont font = WhichFont(type, size);
223    asc = des = 0;
224    for (int i = 0; i < ls; ++i) {
225       if (font.descent(s[i]) > des)
226         des = font.descent(s[i]);
227       if (font.ascent(s[i]) > asc)
228         asc = font.ascent(s[i]);
229    }
230    return asc + des;
231 }
232
233
234 int mathed_char_height(short type, int size, byte c, int & asc, int & des)
235 {
236    LyXFont font = WhichFont(type, size);
237    asc = des = 0;
238    des = font.descent(c);
239    asc = font.ascent(c);
240    return asc + des;
241 }
242
243
244 // In a near future maybe we use a better fonts renderer
245 void MathedInset::drawStr(Painter & pain, short type, int size,
246                           int x, int y, byte * s, int ls)
247 {
248         string st;
249         if (MathIsBinary(type)) {
250                 for (int i = 0; i < ls; ++i) {
251                         st += string(" ") + char(s[i]) + ' ';
252                 }
253         } else {
254                 st = string(reinterpret_cast<char*>(s), ls);
255         }
256         LyXFont mf = mathed_get_font(type, size);
257         pain.text(x, y, st, mf);
258 }
259
260
261 InsetFormula::InsetFormula(bool display)
262 {
263   par = new MathParInset; // this leaks
264   //   mathcursor = 0;
265   disp_flag = display;
266   //label = 0;
267   if (disp_flag) {
268     par->SetType(LM_OT_PAR);
269     par->SetStyle(LM_ST_DISPLAY);
270   }
271 }
272
273
274 InsetFormula::InsetFormula(MathParInset * p)
275 {
276    par = (p->GetType()>= LM_OT_MPAR) ? 
277          new MathMatrixInset(static_cast<MathMatrixInset*>(p)): 
278          new MathParInset(p);
279 //   mathcursor = 0;
280    
281    disp_flag = (par->GetType()>0);
282    //label = 0;
283 }
284
285
286 InsetFormula::~InsetFormula()
287 {
288    delete par;
289 }
290
291
292 Inset * InsetFormula::Clone() const
293 {
294     InsetFormula * f = new InsetFormula(par);
295     f->label = label;
296     return f;
297 }
298
299
300 void InsetFormula::Write(ostream & os) const
301 {
302         os << "Formula ";
303         Latex(os, 0);
304 }
305
306
307 int InsetFormula::Latex(ostream & os, signed char fragile) const
308 {
309     int ret = 0;      
310 //#warning Alejandro, the number of lines is not returned in this case
311 // This problem will disapear at 0.13.
312     string output;
313     InsetFormula::Latex(output, fragile);
314     os << output;
315     return ret;
316 }
317
318
319 int InsetFormula::Latex(string & file, signed char fragile) const
320 {
321     int ret = 0;
322 //#warning Alejandro, the number of lines is not returned in this case
323 // This problem will disapear at 0.13.
324     if (fragile < 0)
325         par->Write(file);
326     else
327         mathed_write(par, file, &ret, fragile, label.c_str());
328     return ret;
329 }
330
331
332 int InsetFormula::Linuxdoc(string &/*file*/) const
333 {
334     return 0;
335 }
336
337
338 int InsetFormula::DocBook(string &/*file*/) const
339 {
340     return 0;
341 }
342
343
344 // Check if uses AMS macros 
345 void InsetFormula::Validate(LaTeXFeatures & features) const
346 {
347     // Validation only necesary if not using an AMS Style
348     if (!features.amsstyle)
349       mathedValidate(features, par);
350 }
351
352
353 void InsetFormula::Read(LyXLex & lex)
354 {
355         istream & is = lex.getStream();
356     
357         mathed_parser_file(is, lex.GetLineNo());   
358    
359         // Silly hack to read labels. 
360         mathed_label = 0;
361         mathed_parse(0, 0, &par);
362         par->Metrics();
363         disp_flag = (par->GetType() > 0);
364         
365         // Update line number
366         lex.setLineNo(mathed_parser_lineno());
367         
368         if (mathed_label) {
369                 label = mathed_label;
370                 mathed_label = 0;
371         }
372    
373 #ifdef DEBUG
374         Write(lyxerr);
375 #endif
376 }
377
378
379 int InsetFormula::ascent(Painter &, LyXFont const &) const
380 {
381    return par->Ascent() + ((disp_flag) ? 8 : 1);
382 }
383
384
385 int InsetFormula::descent(Painter &, LyXFont const &) const
386 {
387    return par->Descent() + ((disp_flag) ? 8 : 1);
388 }
389
390
391 int InsetFormula::width(Painter &, LyXFont const & f) const
392 {
393     lfont_size = f.size();
394     par->Metrics();
395     return par->Width(); //+2;
396 }
397
398
399 void InsetFormula::draw(Painter & pain, LyXFont const &,
400                         int baseline, float & x) const
401 {
402         LyXFont font = mathed_get_font(LM_TC_TEXTRM, LM_ST_TEXT);
403
404         lfont_size = font.size();
405         /// Let's try to wait a bit with this... (Lgb)
406         //UpdatableInset::draw(pain, font, baseline, x);
407         
408         // otherwise a segfault could occur
409         // in some XDrawRectangles (i.e. matrix) (Matthias)
410         if (mathcursor && mathcursor->GetPar() == par) { 
411                 if (mathcursor->Selection()) {
412                         int n;
413                         int * xp = 0;
414                         int * yp = 0;
415                         mathcursor->SelGetArea(&xp, &yp, n);
416                         pain.fillPolygon(xp, yp, n, LColor::selection);
417                 }
418                 mathcursor->draw(pain, int(x), baseline);
419         } else {
420                 par->draw(pain, int(x), baseline);
421         }
422         x += float(width(pain, font));
423         
424         if (par->GetType() == LM_OT_PARN || par->GetType() == LM_OT_MPARN) {
425                 LyXFont font = WhichFont(LM_TC_BF, par->size);
426                 font.setLatex(LyXFont::OFF);
427                 
428                 if (par->GetType() == LM_OT_PARN) {
429                         string str;
430                         if (!label.empty())
431                                 str = string("(") + label + ")";
432                         else
433                                 str = string("(#)");
434                         pain.text(int(x + 20), baseline, str, font);
435                 } else if (par->GetType() == LM_OT_MPARN) {
436                         MathMatrixInset * mt =
437                                 static_cast<MathMatrixInset*>(par);
438                         int y;
439                         MathedRowSt const * crow = mt->getRowSt();
440                         while (crow) {
441                                 y = baseline + crow->getBaseline();
442                                 if (crow->isNumbered()) {
443                                         string str;
444                                         if (crow->getLabel())
445                                                 str = string("(") + crow->getLabel() + ")";
446                                         else
447                                                 str = "(#)";
448                                         pain.text(int(x + 20), y, str, font);
449                                 }
450                                 crow = crow->getNext();
451                         }
452                 }
453         }
454         cursor_visible = false;
455 }
456
457
458 void InsetFormula::Edit(BufferView * bv, int x, int y)
459 {
460    mathcursor = new MathedCursor(par);
461    bv->lockInset(this);
462    par->Metrics();
463    UpdateInset(bv, this, false);
464    x += par->xo; 
465    y += par->yo; 
466    mathcursor->SetPos(x, y);
467     sel_x = sel_y = 0;
468     sel_flag = false;
469 }
470
471
472 void InsetFormula::InsetUnlock(BufferView * bv)
473 {
474    if (mathcursor) {
475        if (mathcursor->InMacroMode()) {
476            mathcursor->MacroModeClose();
477            UpdateLocal(bv);
478        }                                         
479      delete mathcursor;
480    }
481    mathcursor = 0;
482    UpdateInset(bv, this, false);
483 }
484
485
486 // Now a symbol can be inserted only if the inset is locked
487 void InsetFormula::InsertSymbol(BufferView * bv, char const * s)
488
489    if (!s || !mathcursor) return;   
490    mathcursor->Interpret(s);
491    UpdateLocal(bv);
492 }
493
494    
495 void InsetFormula::GetCursorPos(int& x, int& y) const
496 {
497     mathcursor->GetPos(x, y);
498     x -= par->xo; 
499     y -= par->yo;
500 }
501
502 void InsetFormula::ToggleInsetCursor(BufferView * bv)
503 {
504   if (!mathcursor)
505     return;
506
507   int x, y;
508   mathcursor->GetPos(x, y);
509 //  x -= par->xo; 
510   y -= par->yo; 
511     LyXFont font = WhichFont(LM_TC_TEXTRM, LM_ST_TEXT);
512   int asc = font.maxAscent();
513   int desc = font.maxDescent();
514   
515   if (cursor_visible)
516     bv->hideLockedInsetCursor();
517   else
518     bv->showLockedInsetCursor(x, y, asc, desc);
519   cursor_visible = !cursor_visible;
520 }
521
522
523 void InsetFormula::ShowInsetCursor(BufferView * bv)
524 {
525   if (!cursor_visible) {
526     if (mathcursor) {
527       int x, y;
528       mathcursor->GetPos(x, y);
529       //  x -= par->xo; 
530       y -= par->yo;
531         LyXFont font = WhichFont(LM_TC_TEXTRM, LM_ST_TEXT);
532         int asc = font.maxAscent();
533         int desc = font.maxDescent();
534       bv->fitLockedInsetCursor(x, y, asc, desc);
535     }
536     ToggleInsetCursor(bv);
537   }
538 }
539
540
541 void InsetFormula::HideInsetCursor(BufferView * bv)
542 {
543   if (cursor_visible)
544     ToggleInsetCursor(bv);
545 }
546
547
548 void InsetFormula::ToggleInsetSelection(BufferView * bv)
549 {
550     if (!mathcursor)
551       return;
552     
553 //    int x, y, w, h;
554     //int n;
555     //XPoint * p = 
556     //mathcursor->SelGetArea(n);
557 //    XFillPolygon(fl_display, pm, LyXGetSelectionGC(), p, n, Nonconvex, CoordModeOrigin);
558 //    x -= par->xo; 
559 //    y -= par->yo;
560
561     UpdateInset(bv, this, false);
562       
563 }
564
565
566 void InsetFormula::display(bool dspf)
567 {
568    if (dspf != disp_flag) {
569       if (dspf) {
570          par->SetType(LM_OT_PAR);
571          par->SetStyle(LM_ST_DISPLAY);
572       } else {
573          if (par->GetType() >= LM_OT_MPAR) { 
574             MathParInset * p = new MathParInset(par);
575             delete par;
576             par = p;
577             if (mathcursor) 
578                mathcursor->SetPar(par); 
579          }
580          par->SetType(LM_OT_MIN);
581          par->SetStyle(LM_ST_TEXT);
582          if (!label.empty() && par->GetType() != LM_OT_MPARN) {
583                  label.clear();
584          }
585       }
586       disp_flag = dspf;
587    }
588 }
589
590
591 int InsetFormula::GetNumberOfLabels() const
592 {
593    // This is dirty, I know. I'll clean it at 0.13
594    if (par->GetType() == LM_OT_MPARN) {
595        MathMatrixInset * mt = static_cast<MathMatrixInset*>(par);
596        int nl = 0;
597        MathedRowSt const * crow = mt->getRowSt();
598        while (crow) {
599            if (crow->getLabel()) ++nl;
600            crow = crow->getNext();
601        }
602        return nl;
603    } else
604    if (!label.empty())
605        return 1;
606    else
607        return 0;
608 }
609
610
611 string InsetFormula::getLabel(int il) const
612 {
613 //#warning This is dirty, I know. Ill clean it at 0.11
614         // Correction, the only way to clean this is with a new kernel: 0.13.
615         if (par->GetType() == LM_OT_MPARN) {
616                 string lab;
617                 MathMatrixInset * mt = static_cast<MathMatrixInset*>(par);
618                 int nl = 0;
619                 MathedRowSt const * crow = mt->getRowSt();
620                 while (crow) {
621                         if (crow->getLabel()) {
622                                 if (nl == il) {
623                                         lab = crow->getLabel();
624                                         break;
625                                 }
626                                 ++nl;
627                         }
628                         crow = crow->getNext();
629                 }
630                 return lab;
631         }
632         return label;
633 }
634
635
636 void InsetFormula::UpdateLocal(BufferView * bv)
637 {
638    par->Metrics();  // To inform lyx kernel the exact size 
639                   // (there were problems with arrays).
640    UpdateInset(bv, this);
641 }
642
643
644 void InsetFormula::InsetButtonRelease(BufferView * bv,
645                                       int x, int y, int /*button*/)
646 {
647     HideInsetCursor(bv);
648     x += par->xo;
649     y += par->yo;
650     mathcursor->SetPos(x, y);
651     ShowInsetCursor(bv);
652     if (sel_flag) {
653         sel_flag = false; 
654         sel_x = sel_y = 0;
655         UpdateInset(bv, this, false); 
656     }
657 }
658
659
660 void InsetFormula::InsetButtonPress(BufferView * bv,
661                                     int x, int y, int /*button*/)
662 {
663     sel_flag = false;
664     sel_x = x;  sel_y = y; 
665     if (mathcursor->Selection()) {
666         mathcursor->SelClear();
667         UpdateInset(bv, this, false); 
668     }
669 }
670
671
672 void InsetFormula::InsetMotionNotify(BufferView * bv,
673                                      int x, int y, int /*button*/)
674 {
675     if (sel_x && sel_y && abs(x-sel_x) > 4 && !sel_flag) {
676         sel_flag = true;
677         HideInsetCursor(bv);
678         mathcursor->SetPos(sel_x + par->xo, sel_y + par->yo);
679         mathcursor->SelStart();
680         ShowInsetCursor(bv); 
681         mathcursor->GetPos(sel_x, sel_y);
682     } else
683       if (sel_flag) {
684           HideInsetCursor(bv);
685           x += par->xo;
686           y += par->yo;
687           mathcursor->SetPos(x, y);
688           ShowInsetCursor(bv);
689           mathcursor->GetPos(x, y);
690           if (sel_x!= x || sel_y!= y)
691             UpdateInset(bv, this, false); 
692           sel_x = x;  sel_y = y;
693       }
694 }
695
696
697 void InsetFormula::InsetKeyPress(XKeyEvent *)
698 {
699         lyxerr[Debug::MATHED] << "Used InsetFormula::InsetKeyPress." << endl;
700 }
701
702
703 // Special Mathed functions
704 bool InsetFormula::SetNumber(bool numbf)
705 {
706    if (disp_flag) {
707       short type = par->GetType();
708       bool oldf = (type == LM_OT_PARN || type == LM_OT_MPARN);
709       if (numbf && !oldf) ++type;
710       if (!numbf && oldf) --type;
711       par->SetType(type);
712       return oldf;
713    } else
714      return false;
715 }
716
717
718 bool InsetFormula::LocalDispatch(BufferView * bv, int action, char const * arg)
719 {
720 //   extern char *dispatch_result;
721     MathedTextCodes varcode = LM_TC_MIN;       
722    bool was_macro = mathcursor->InMacroMode();
723    bool sel = false;
724    bool space_on = false;
725    bool was_selection = mathcursor->Selection();
726    bool result = true;
727    static MathSpaceInset * sp= 0;
728
729    HideInsetCursor(bv);
730
731     if (mathcursor->getLastCode() == LM_TC_TEX) { 
732         varcode = LM_TC_TEX;
733     }
734    switch (action) {
735        
736     // --- Cursor Movements ---------------------------------------------
737     case LFUN_RIGHTSEL: sel = true;
738     case LFUN_RIGHT:
739       {
740          result = mathcursor->Right(sel);
741          break;
742       }
743     case LFUN_LEFTSEL: sel = true;     
744     case LFUN_LEFT:
745       {
746          result = mathcursor->Left(sel);
747          break;
748       }
749     case LFUN_UPSEL: sel = true;  
750     case LFUN_UP:
751       result = mathcursor->Up(sel);
752       break;
753        
754     case LFUN_DOWNSEL: sel = true;  
755     case LFUN_DOWN:
756       result = mathcursor->Down(sel);
757       break;
758     case LFUN_HOME:
759       mathcursor->Home();
760       break;
761     case LFUN_END:
762       mathcursor->End();
763       break;
764     case LFUN_DELETE_LINE_FORWARD:
765             //current_view->lockedInsetStoreUndo(Undo::INSERT);
766             bv->lockedInsetStoreUndo(Undo::DELETE);
767       mathcursor->DelLine();
768       UpdateLocal(bv);
769       break;
770     case LFUN_BREAKLINE:
771       bv->lockedInsetStoreUndo(Undo::INSERT);
772       mathcursor->Insert(' ', LM_TC_CR);
773       par = mathcursor->GetPar();
774       UpdateLocal(bv);
775       break;
776     case LFUN_TAB:
777       bv->lockedInsetStoreUndo(Undo::INSERT);
778       mathcursor->Insert(0, LM_TC_TAB);
779       //UpdateInset(this);
780       break;     
781     case LFUN_TABINSERT:
782       bv->lockedInsetStoreUndo(Undo::INSERT);
783       mathcursor->Insert('T', LM_TC_TAB);
784       UpdateLocal(bv);
785       break;     
786     case LFUN_BACKSPACE:
787        if (!mathcursor->Left()) 
788          break;
789        
790        if (!mathcursor->InMacroMode() && mathcursor->pullArg()) {       
791            UpdateInset(bv, this);
792            break;
793        }
794       
795     case LFUN_DELETE:
796             //current_view->lockedInsetStoreUndo(Undo::INSERT);
797             bv->lockedInsetStoreUndo(Undo::DELETE);
798       mathcursor->Delete();       
799       UpdateInset(bv, this);
800       break;    
801 //    case LFUN_GETXY:
802 //      sprintf(dispatch_buffer, "%d %d",);
803 //      dispatch_result = dispatch_buffer;
804 //      break;
805     case LFUN_SETXY:
806       {
807          int x, y, x1, y1;
808          sscanf(arg, "%d %d", &x, &y);
809          par->GetXY(x1, y1);
810          mathcursor->SetPos(x1+x, y1+y);
811       }
812       break;
813
814       /* cursor selection ---------------------------- */
815
816     case LFUN_PASTE:
817             if (was_macro)
818                 mathcursor->MacroModeClose();
819             bv->lockedInsetStoreUndo(Undo::INSERT);
820             mathcursor->SelPaste(); UpdateLocal(bv); break;
821     case LFUN_CUT:
822             bv->lockedInsetStoreUndo(Undo::DELETE);
823             mathcursor->SelCut(); UpdateLocal(bv); break;
824     case LFUN_COPY: mathcursor->SelCopy(); break;      
825     case LFUN_HOMESEL:
826     case LFUN_ENDSEL:
827     case LFUN_WORDRIGHTSEL:
828     case LFUN_WORDLEFTSEL:
829       break;
830       
831     // --- accented characters ------------------------------
832
833     case LFUN_UMLAUT: mathcursor->setAccent(LM_ddot); break;
834     case LFUN_CIRCUMFLEX: mathcursor->setAccent(LM_hat); break;
835     case LFUN_GRAVE: mathcursor->setAccent(LM_grave); break;
836     case LFUN_ACUTE: mathcursor->setAccent(LM_acute); break;
837     case LFUN_TILDE: mathcursor->setAccent(LM_tilde); break;
838     case LFUN_MACRON: mathcursor->setAccent(LM_bar); break;
839     case LFUN_DOT: mathcursor->setAccent(LM_dot); break;
840     case LFUN_CARON: mathcursor->setAccent(LM_check); break;
841     case LFUN_BREVE: mathcursor->setAccent(LM_breve); break;
842     case LFUN_VECTOR: mathcursor->setAccent(LM_vec); break; 
843       
844     // Greek mode     
845     case LFUN_GREEK:
846     {
847        if (!greek_kb_flag) {
848           greek_kb_flag = 1;
849           bv->owner()->getMiniBuffer()->Set(_("Math greek mode on"));
850        } else
851          greek_kb_flag = 0;
852        break;
853     }  
854       
855     // Greek keyboard      
856     case LFUN_GREEK_TOGGLE:
857     {
858        greek_kb_flag = (greek_kb_flag) ? 0 : 2;
859        if (greek_kb_flag)
860          bv->owner()->getMiniBuffer()->Set(_("Math greek keyboard on"));
861        else
862          bv->owner()->getMiniBuffer()->Set(_("Math greek keyboard off"));
863        break;
864     }  
865    
866       //  Math fonts 
867     case LFUN_BOLD:     mathcursor->setLastCode(LM_TC_BF); break;
868     case LFUN_SANS:  mathcursor->setLastCode( LM_TC_SF); break;
869     case LFUN_EMPH:  mathcursor->setLastCode(LM_TC_CAL); break;
870     case LFUN_ROMAN: mathcursor->setLastCode(LM_TC_RM); break;
871     case LFUN_CODE: mathcursor->setLastCode(LM_TC_TT); break;   
872     case LFUN_DEFAULT:  mathcursor->setLastCode(LM_TC_VAR ) ; break;
873     case LFUN_TEX: 
874     {
875 //       varcode = LM_TC_TEX;
876         mathcursor->setLastCode(LM_TC_TEX);
877         bv->owner()->getMiniBuffer()->Set(_("TeX mode")); 
878        break;
879     }
880
881     case LFUN_MATH_NUMBER:
882     {
883       bv->lockedInsetStoreUndo(Undo::INSERT);
884        if (disp_flag) {
885           short type = par->GetType();
886           bool oldf = (type == LM_OT_PARN || type == LM_OT_MPARN);
887           if (oldf) {
888              --type;
889              if (!label.empty()) {
890                      label.clear();
891              }
892              bv->owner()->getMiniBuffer()->Set(_("No number"));  
893           } else {
894              ++type;
895              bv->owner()->getMiniBuffer()->Set(_("Number"));
896           }
897           par->SetType(type);
898           UpdateLocal(bv);
899        }
900        break;
901     }
902     
903     case LFUN_MATH_NONUMBER:
904     { 
905         if (par->GetType() == LM_OT_MPARN) {
906 //         MathMatrixInset *mt = (MathMatrixInset*)par;
907            //BUG 
908 //         mt->SetNumbered(!mt->IsNumbered());
909             
910             mathcursor->setNumbered();
911            UpdateLocal(bv);
912         }
913         break;
914     }
915        
916     case LFUN_MATH_LIMITS:
917     {
918       bv->lockedInsetStoreUndo(Undo::INSERT);
919        if (mathcursor->Limits())
920          UpdateLocal(bv);
921     }
922  
923     case LFUN_MATH_SIZE:
924        if (arg) {
925            latexkeys * l = in_word_set (arg, strlen(arg));
926            int sz = (l) ? l->id: -1;
927            mathcursor->SetSize(sz);
928            UpdateLocal(bv);
929            break;
930        }
931        
932     case LFUN_INSERT_MATH:
933     {
934         bv->lockedInsetStoreUndo(Undo::INSERT);
935         InsertSymbol(bv, arg);
936         break;
937     }
938     
939     case LFUN_INSERT_MATRIX:
940     { 
941       bv->lockedInsetStoreUndo(Undo::INSERT);
942        int k, m, n;
943        char s[80], arg2[80];
944        // This is just so that too long args won't ooze out of s.
945        strncpy(arg2, arg, 80); arg2[79]= '\0';
946        k = sscanf(arg2, "%d %d %s", &m, &n, s);
947        s[79] = '\0';
948         
949        if (k < 1) {
950            m = n = 1;
951        } else if (k == 1) {
952            n = 1;
953        }
954         
955        MathMatrixInset * p = new MathMatrixInset(m, n);      
956        if (mathcursor && p) {
957           if (k > 2 && int(strlen(s)) > m)
958             p->SetAlign(s[0], &s[1]);
959           mathcursor->Insert(p, LM_TC_ACTIVE_INSET);
960           UpdateLocal(bv);
961        }
962        break;
963     }
964       
965     case LFUN_MATH_DELIM:
966     {  
967       bv->lockedInsetStoreUndo(Undo::INSERT);
968        char lf[40], rg[40], arg2[40];
969        int ilf = '(', irg = '.';
970        latexkeys * l;
971        string vdelim("(){}[]./|");
972         
973        if (!arg) break;
974        strncpy(arg2, arg, 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)  {
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 = false;
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 =  false;
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)
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 }