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