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