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