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