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