]> git.lyx.org Git - lyx.git/blob - src/mathed/formula.C
6d7f75a58816dc32792a15f1ec35f1d66b8194fd
[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
41 using std::ostream;
42 using std::istream;
43 using std::pair;
44 using std::endl;
45 using std::vector;
46 using std::max;
47
48 //extern char * mathed_label;
49 extern string mathed_label;
50
51 extern char const * latex_special_chars;
52
53 int greek_kb_flag = 0;
54
55 LyXFont * Math_Fonts = 0; // this is only used by Whichfont and mathed_init_fonts (Lgb)
56
57 static LyXFont::FONT_SIZE lfont_size = LyXFont::SIZE_NORMAL;
58
59 // local global
60 static int sel_x;
61 static int sel_y;
62 static bool sel_flag;
63
64 MathedCursor * InsetFormula::mathcursor = 0; 
65
66
67 int MathedInset::df_asc;
68 int MathedInset::df_des;
69 int MathedInset::df_width;
70
71
72 inline
73 bool IsMacro(short token, int id)
74 {
75    return (token != LM_TK_FRAC && token != LM_TK_SQRT &&
76           !((token == LM_TK_SYM || token == LM_TC_BSYM) && id < 255));
77 }
78
79
80 static
81 void mathedValidate(LaTeXFeatures & features, MathParInset * par);
82
83
84 LyXFont WhichFont(short type, int size)
85 {
86     LyXFont f;
87     
88       if (!Math_Fonts)
89         mathed_init_fonts();
90    
91    switch (type) {
92     case LM_TC_SYMB:         
93       f = Math_Fonts[2];
94       break;
95     case LM_TC_BSYM:         
96       f = Math_Fonts[2];
97       break;
98     case LM_TC_VAR:
99     case LM_TC_IT:
100       f = Math_Fonts[0];
101       break;
102     case LM_TC_BF:
103       f = Math_Fonts[3];
104       break;
105     case LM_TC_SF:
106       f = Math_Fonts[7];
107       break;
108     case LM_TC_CAL:
109       f = Math_Fonts[4];
110       break;
111     case LM_TC_TT:
112       f = Math_Fonts[5];
113       break;
114     case LM_TC_SPECIAL: //f = Math_Fonts[0]; break;
115     case LM_TC_TEXTRM:
116     case LM_TC_RM:    
117       f = Math_Fonts[6];
118       break;
119     default:
120       f = Math_Fonts[1];
121       break;   
122    }
123     
124     f.setSize(lfont_size);
125     
126     switch (size) {
127      case LM_ST_DISPLAY:     
128         if (type == LM_TC_BSYM) {
129             f.incSize();
130             f.incSize();
131         }
132         break;
133      case LM_ST_TEXT:
134         break;
135      case LM_ST_SCRIPT:
136         f.decSize();
137         break;
138      case LM_ST_SCRIPTSCRIPT:
139         f.decSize();
140         f.decSize();
141         break;
142      default:
143              lyxerr << "Mathed Error: wrong font size: " << size << endl;
144         break;
145     }
146
147     if (type != LM_TC_TEXTRM) 
148       f.setColor(LColor::math);
149     return f;
150 }
151
152
153 void mathed_init_fonts() //removed 'static' because DEC cxx does not
154                          //like it (JMarc)
155         // Probably because this func is declared as a friend in math_defs.h
156         // Lgb
157 {
158
159     Math_Fonts = new LyXFont[8]; //DEC cxx cannot initialize all fonts
160                                  //at once (JMarc) rc
161     for (int i = 0 ; i < 8 ; ++i) { 
162         Math_Fonts[i] = LyXFont(LyXFont::ALL_SANE);
163     }
164     Math_Fonts[0].setShape(LyXFont::ITALIC_SHAPE);
165     
166     Math_Fonts[1].setFamily(LyXFont::SYMBOL_FAMILY);
167     
168     Math_Fonts[2].setFamily(LyXFont::SYMBOL_FAMILY);
169     Math_Fonts[2].setShape(LyXFont::ITALIC_SHAPE);
170
171     Math_Fonts[3].setSeries(LyXFont::BOLD_SERIES);
172       
173     Math_Fonts[4].setFamily(LyXFont::SANS_FAMILY);
174     Math_Fonts[4].setShape(LyXFont::ITALIC_SHAPE);
175       
176     Math_Fonts[5].setFamily(LyXFont::TYPEWRITER_FAMILY);
177
178     Math_Fonts[6].setFamily(LyXFont::ROMAN_FAMILY);
179
180     Math_Fonts[7].setFamily(LyXFont::SANS_FAMILY);
181     
182     LyXFont f = WhichFont(LM_TC_VAR, LM_ST_TEXT);
183     MathedInset::df_asc = lyxfont::maxAscent(f); 
184     MathedInset::df_des = lyxfont::maxDescent(f);
185     MathedInset::df_width = lyxfont::width('I', f);    
186 }
187
188
189 LyXFont mathed_get_font(short type, int size)
190 {
191         LyXFont f = WhichFont(type, size);
192         if (type == LM_TC_TEX) {
193                 f.setLatex(LyXFont::ON);
194         }
195         return f;
196 }
197
198
199 int mathed_string_width(short type, int size, byte const * s, int ls)
200 {
201     LyXFont f = WhichFont(type, size);
202
203     byte sx[80];
204     if (MathIsBinary(type)) {
205         byte * ps = &sx[0];
206         for (int i = 0; i < ls && i < 75; ++i) {
207             *(ps++) = ' ';
208             *(ps++) = s[i];
209             *(ps++) = ' ';
210         }
211         *(ps++) = '\0';
212         ls *= 3;
213         s = &sx[0];
214     }
215     return lyxfont::width(reinterpret_cast<char const *>(s), ls, f);
216 }
217
218 int mathed_string_width(short type, int size, string const & str)
219 {
220         return mathed_string_width(type, size, reinterpret_cast<unsigned char const *>(str.c_str()), str.length());
221 }
222
223
224 int mathed_char_width(short type, int size, byte c)
225 {
226     int t = (MathIsBinary(type)) ? mathed_string_width(type, size, &c, 1) :
227            lyxfont::width(c, WhichFont(type, size));
228     return t;
229 }
230
231
232 int mathed_string_height(short type, int size, byte const * s,
233                          int ls, int & asc, int & des)
234 {
235    LyXFont font = WhichFont(type, size);
236    asc = des = 0;
237    for (int i = 0; i < ls; ++i) {
238       des = max(des, lyxfont::descent(s[i], font));
239       asc = max(asc, lyxfont::ascent(s[i], font));
240    }
241    return asc + des;
242 }
243
244
245 int mathed_string_height(short type, int size, string const & str,
246                          int & asc, int & des)
247 {
248         return mathed_string_height(type, size,
249                                     reinterpret_cast<unsigned char const *>(str.c_str()), str.length(),
250                                     asc, des);
251 }
252
253
254 int mathed_char_height(short type, int size, byte c, int & asc, int & des)
255 {
256    LyXFont font = WhichFont(type, size);
257    des = lyxfont::descent(c, font);
258    asc = lyxfont::ascent(c, font);
259    return asc + des;
260 }
261
262
263 // In a near future maybe we use a better fonts renderer
264 void MathedInset::drawStr(Painter & pain, short type, int siz,
265                           int x, int y, byte const * s, int ls)
266 {
267         string st;
268         if (MathIsBinary(type)) {
269                 for (int i = 0; i < ls; ++i) {
270                         st += string(" ") + char(s[i]) + ' ';
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() 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)
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_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             //current_view->lockedInsetStoreUndo(Undo::INSERT);
792             bv->lockedInsetStoreUndo(Undo::DELETE);
793       mathcursor->DelLine();
794       UpdateLocal(bv);
795       break;
796     case LFUN_BREAKLINE:
797       bv->lockedInsetStoreUndo(Undo::INSERT);
798       mathcursor->Insert(' ', LM_TC_CR);
799       par = mathcursor->GetPar();
800       UpdateLocal(bv);
801       break;
802     case LFUN_TAB:
803       bv->lockedInsetStoreUndo(Undo::INSERT);
804       mathcursor->Insert(0, LM_TC_TAB);
805       //UpdateInset(this);
806       break;     
807     case LFUN_TABINSERT:
808       bv->lockedInsetStoreUndo(Undo::INSERT);
809       mathcursor->Insert('T', LM_TC_TAB);
810       UpdateLocal(bv);
811       break;     
812     case LFUN_BACKSPACE:
813        if (!mathcursor->Left()) 
814          break;
815        
816        if (!mathcursor->InMacroMode() && mathcursor->pullArg()) {       
817            bv->updateInset(this, true);
818            break;
819        }
820       
821     case LFUN_DELETE:
822             //current_view->lockedInsetStoreUndo(Undo::INSERT);
823             bv->lockedInsetStoreUndo(Undo::DELETE);
824       mathcursor->Delete();       
825       bv->updateInset(this, true);
826       break;    
827 //    case LFUN_GETXY:
828 //      sprintf(dispatch_buffer, "%d %d",);
829 //      dispatch_result = dispatch_buffer;
830 //      break;
831     case LFUN_SETXY:
832       {
833          int x;
834          int y;
835          int x1;
836          int y1;
837          istringstream ist(arg.c_str());
838          ist >> x >> y;
839          par->GetXY(x1, y1);
840          mathcursor->SetPos(x1 + x, y1 + y);
841       }
842       break;
843
844       /* cursor selection ---------------------------- */
845
846     case LFUN_PASTE:
847             if (was_macro)
848                 mathcursor->MacroModeClose();
849             bv->lockedInsetStoreUndo(Undo::INSERT);
850             mathcursor->SelPaste(); UpdateLocal(bv); break;
851     case LFUN_CUT:
852             bv->lockedInsetStoreUndo(Undo::DELETE);
853             mathcursor->SelCut(); UpdateLocal(bv); break;
854     case LFUN_COPY: mathcursor->SelCopy(); break;      
855     case LFUN_HOMESEL:
856     case LFUN_ENDSEL:
857     case LFUN_WORDRIGHTSEL:
858     case LFUN_WORDLEFTSEL:
859       break;
860       
861     // --- accented characters ------------------------------
862
863     case LFUN_UMLAUT: mathcursor->setAccent(LM_ddot); break;
864     case LFUN_CIRCUMFLEX: mathcursor->setAccent(LM_hat); break;
865     case LFUN_GRAVE: mathcursor->setAccent(LM_grave); break;
866     case LFUN_ACUTE: mathcursor->setAccent(LM_acute); break;
867     case LFUN_TILDE: mathcursor->setAccent(LM_tilde); break;
868     case LFUN_MACRON: mathcursor->setAccent(LM_bar); break;
869     case LFUN_DOT: mathcursor->setAccent(LM_dot); break;
870     case LFUN_CARON: mathcursor->setAccent(LM_check); break;
871     case LFUN_BREVE: mathcursor->setAccent(LM_breve); break;
872     case LFUN_VECTOR: mathcursor->setAccent(LM_vec); break; 
873       
874     // Greek mode     
875     case LFUN_GREEK:
876     {
877        if (!greek_kb_flag) {
878           greek_kb_flag = 1;
879           bv->owner()->getMiniBuffer()->Set(_("Math greek mode on"));
880        } else
881          greek_kb_flag = 0;
882        break;
883     }  
884       
885     // Greek keyboard      
886     case LFUN_GREEK_TOGGLE:
887     {
888        greek_kb_flag = (greek_kb_flag) ? 0 : 2;
889        if (greek_kb_flag)
890          bv->owner()->getMiniBuffer()->Set(_("Math greek keyboard on"));
891        else
892          bv->owner()->getMiniBuffer()->Set(_("Math greek keyboard off"));
893        break;
894     }  
895    
896       //  Math fonts 
897     case LFUN_BOLD:     mathcursor->setLastCode(LM_TC_BF); break;
898     case LFUN_SANS:  mathcursor->setLastCode( LM_TC_SF); break;
899     case LFUN_EMPH:  mathcursor->setLastCode(LM_TC_CAL); break;
900     case LFUN_ROMAN: mathcursor->setLastCode(LM_TC_RM); break;
901     case LFUN_CODE: mathcursor->setLastCode(LM_TC_TT); break;   
902     case LFUN_DEFAULT:  mathcursor->setLastCode(LM_TC_VAR ) ; break;
903     case LFUN_TEX: 
904     {
905 //       varcode = LM_TC_TEX;
906         mathcursor->setLastCode(LM_TC_TEX);
907         bv->owner()->getMiniBuffer()->Set(_("TeX mode")); 
908        break;
909     }
910
911     case LFUN_MATH_NUMBER:
912     {
913       bv->lockedInsetStoreUndo(Undo::INSERT);
914        if (disp_flag) {
915           short type = par->GetType();
916           bool oldf = (type == LM_OT_PARN || type == LM_OT_MPARN);
917           if (oldf) {
918              --type;
919              if (!label.empty()) {
920                      label.erase();
921              }
922              bv->owner()->getMiniBuffer()->Set(_("No number"));  
923           } else {
924              ++type;
925              bv->owner()->getMiniBuffer()->Set(_("Number"));
926           }
927           par->SetType(type);
928           UpdateLocal(bv);
929        }
930        break;
931     }
932     
933     case LFUN_MATH_NONUMBER:
934     { 
935         if (par->GetType() == LM_OT_MPARN) {
936 //         MathMatrixInset *mt = (MathMatrixInset*)par;
937            //BUG 
938 //         mt->SetNumbered(!mt->IsNumbered());
939             
940             mathcursor->setNumbered();
941            UpdateLocal(bv);
942         }
943         break;
944     }
945        
946     case LFUN_MATH_LIMITS:
947     {
948       bv->lockedInsetStoreUndo(Undo::INSERT);
949        if (mathcursor->Limits())
950          UpdateLocal(bv);
951     }
952  
953     case LFUN_MATH_SIZE:
954        if (!arg.empty()) {
955            latexkeys * l = in_word_set (arg);
956            int sz = (l) ? l->id: -1;
957            mathcursor->SetSize(sz);
958            UpdateLocal(bv);
959            break;
960        }
961        
962     case LFUN_INSERT_MATH:
963     {
964         bv->lockedInsetStoreUndo(Undo::INSERT);
965         InsertSymbol(bv, arg);
966         break;
967     }
968     
969     case LFUN_INSERT_MATRIX:
970     { 
971       bv->lockedInsetStoreUndo(Undo::INSERT);
972        int k, m, n;
973        char s[80], arg2[80];
974        // This is just so that too long args won't ooze out of s.
975        strncpy(arg2, arg.c_str(), 80); arg2[79]= '\0';
976        k = sscanf(arg2, "%d %d %s", &m, &n, s);
977        s[79] = '\0';
978         
979        if (k < 1) {
980            m = n = 1;
981        } else if (k == 1) {
982            n = 1;
983        }
984         
985        MathMatrixInset * p = new MathMatrixInset(m, n);      
986        if (mathcursor && p) {
987           if (k > 2 && int(strlen(s)) > m)
988             p->SetAlign(s[0], &s[1]);
989           mathcursor->Insert(p, LM_TC_ACTIVE_INSET);
990           UpdateLocal(bv);
991        }
992        break;
993     }
994       
995     case LFUN_MATH_DELIM:
996     {  
997       bv->lockedInsetStoreUndo(Undo::INSERT);
998        char lf[40], rg[40], arg2[40];
999        int ilf = '(', irg = '.';
1000        latexkeys * l;
1001        string vdelim("(){}[]./|");
1002         
1003        if (arg.empty())
1004                break;
1005        strncpy(arg2, arg.c_str(), 40); arg2[39]= '\0';
1006        int n = sscanf(arg2, "%s %s", lf, rg);
1007        lf[39] = '\0'; rg[39] = '\0';
1008
1009        if (n > 0) {
1010            if (isdigit(lf[0])) 
1011              ilf = lyx::atoi(lf);
1012            else 
1013              if (lf[1]) {
1014                  l = in_word_set(lf, strlen(lf));
1015                  // Long words will cause l == 0; so check.
1016                  if(l) ilf = l->id;
1017              } else
1018              if (vdelim.find(lf[0]) != string::npos)
1019                ilf = lf[0];
1020            
1021            if (n > 1) {
1022                if (isdigit(rg[0]))
1023                  irg = lyx::atoi(rg);
1024                else 
1025                  if (rg[1]) {
1026                      l = in_word_set(rg, strlen(rg));
1027                      if(l) irg = l->id;
1028                  } else
1029                  if (vdelim.find(rg[0]) != string::npos)
1030                    irg = rg[0];
1031            }
1032        }
1033        
1034        MathDelimInset * p = new MathDelimInset(ilf, irg);
1035        mathcursor->Insert(p, LM_TC_ACTIVE_INSET);
1036        UpdateLocal(bv);
1037        break;
1038     }
1039
1040     case LFUN_PROTECTEDSPACE:
1041     {
1042       bv->lockedInsetStoreUndo(Undo::INSERT);
1043        sp = new MathSpaceInset(1); 
1044        mathcursor->Insert(sp);
1045        space_on = true;
1046        UpdateLocal(bv);
1047        break;
1048     }
1049       
1050     case LFUN_INSERT_LABEL:
1051     {
1052        bv->lockedInsetStoreUndo(Undo::INSERT);
1053        if (par->GetType() < LM_OT_PAR) break;
1054        string lb = arg;
1055        if (lb.empty()) {
1056           pair<bool, string>
1057                 res = askForText(_("Enter new label to insert:"));
1058           if (res.first) {
1059              lb = res.second;
1060           }
1061        }
1062        if (!lb.empty() && lb[0] > ' ') {
1063           SetNumber(true);
1064           if (par->GetType() == LM_OT_MPARN) {
1065               mathcursor->setLabel(lb);
1066 //            MathMatrixInset *mt = (MathMatrixInset*)par;
1067 //            mt->SetLabel(lb);
1068           } else {
1069                   //if (label.notEmpty()) delete label;
1070               label = lb;
1071           }
1072           UpdateLocal(bv);
1073        } else
1074                label.erase();
1075        break;
1076     }
1077     
1078     case LFUN_MATH_DISPLAY:
1079             //current_view->lockedInsetStoreUndo(Undo::INSERT);
1080             bv->lockedInsetStoreUndo(Undo::EDIT);
1081       display(!disp_flag);
1082       UpdateLocal(bv);
1083       break;
1084       
1085     // Invalid actions under math mode
1086     case LFUN_MATH_MODE:  
1087     {
1088         if (mathcursor->getLastCode()!= LM_TC_TEXTRM) {
1089             bv->owner()->getMiniBuffer()->Set(_("math text mode"));
1090             varcode = LM_TC_TEXTRM;
1091         } else {
1092             varcode = LM_TC_VAR;
1093         }
1094         mathcursor->setLastCode(varcode);
1095         break; 
1096     }
1097     case LFUN_UNDO:
1098       bv->owner()->getMiniBuffer()->Set(_("Invalid action in math mode!"));
1099       break;
1100
1101     //------- dummy actions
1102     case LFUN_EXEC_COMMAND:
1103        bv->owner()->getMiniBuffer()->ExecCommand(); 
1104        break;
1105        
1106     default:
1107       if ((action == -1  || action == LFUN_SELFINSERT) && !arg.empty())  {
1108          unsigned char c = arg[0];
1109          bv->lockedInsetStoreUndo(Undo::INSERT);
1110          
1111          if (c == ' ' && mathcursor->getAccent() == LM_hat) {
1112              c = '^';
1113              mathcursor->setAccent(0);
1114          }
1115          if (c == 0) {      // Dead key, do nothing 
1116              //lyxerr << "deadkey" << endl;
1117              break;
1118          } 
1119          if (isalpha(c)) {
1120              if (mathcursor->getLastCode() == LM_TC_TEX) { 
1121                mathcursor->MacroModeOpen();
1122                mathcursor->clearLastCode();
1123                varcode = LM_TC_MIN;
1124             } else          
1125             if (!varcode) {             
1126                 short f = (mathcursor->getLastCode()) ? 
1127                           mathcursor->getLastCode() :
1128                           static_cast<MathedTextCodes>(mathcursor->GetFCode());
1129                 varcode = MathIsAlphaFont(f) ?
1130                         static_cast<MathedTextCodes>(f) :
1131                         LM_TC_VAR;
1132             }
1133
1134 //           lyxerr << "Varcode << vardoce;
1135             MathedTextCodes char_code = varcode;
1136             if (greek_kb_flag) {
1137                     char greek[26] = 
1138                     {'A', 'B', 'X',  0 , 'E',  0 ,  0 , 'H', 'I',  0 ,
1139                      'K',  0 , 'M', 'N', 'O',  0 ,  0 , 'P',  0 , 'T',
1140                      'Y',  0,   0,   0,   0 , 'Z' };
1141                     if ('A' <= c && c <= 'Z' && greek[c - 'A']) {
1142                             char_code = LM_TC_RM;
1143                             c = greek[c - 'A'];
1144                     } else
1145                             char_code = LM_TC_SYMB;
1146             }
1147             mathcursor->Insert(c, char_code);
1148             if (greek_kb_flag && char_code == LM_TC_RM )
1149                     mathcursor->setLastCode(LM_TC_VAR);
1150             varcode = LM_TC_MIN;
1151             if (greek_kb_flag<2) greek_kb_flag = 0;
1152          } else 
1153            if (strchr("!,:;{}", c) && (varcode == LM_TC_TEX||was_macro)) {
1154                mathcursor->Insert(c, LM_TC_TEX);
1155                if (c == '{') {
1156                    mathcursor->Insert('}', LM_TC_TEX);
1157                    mathcursor->Left();
1158                }
1159                mathcursor->clearLastCode();
1160 //             varcode = LM_TC_MIN;
1161            } else
1162            if (c == '_' && varcode == LM_TC_TEX) {
1163                mathcursor->Insert(c, LM_TC_SPECIAL);
1164                mathcursor->clearLastCode();
1165 //             varcode = LM_TC_MIN;
1166            } else
1167             if (('0'<= c && c<= '9') && (varcode == LM_TC_TEX||was_macro)) {
1168                 mathcursor->MacroModeOpen();
1169                 mathcursor->clearLastCode();
1170                 mathcursor->Insert(c, LM_TC_MIN);
1171             }
1172          else
1173            if (('0'<= c && c<= '9') || strchr(";:!|[]().,?", c)) 
1174               mathcursor->Insert(c, LM_TC_CONST);
1175          else
1176            if (strchr("+/-*<>=", c))
1177               mathcursor->Insert(c, LM_TC_BOP);
1178          else
1179            if (strchr(latex_special_chars, c) && c!= '_')
1180               mathcursor->Insert(c, LM_TC_SPECIAL);
1181          else
1182            if (c == '_' || c == '^') {
1183                char s[2];
1184                s[0] = c;
1185                s[1] = 0;
1186               mathcursor->Interpret (s);
1187            } else
1188            if (c == ' ') {          
1189                if (!varcode) {  
1190                    short f = (mathcursor->getLastCode()) ? 
1191                               mathcursor->getLastCode() :
1192                               static_cast<MathedTextCodes>(mathcursor->GetFCode());
1193                    varcode = MathIsAlphaFont(f) ?
1194                            static_cast<MathedTextCodes>(f) :
1195                            LM_TC_VAR;
1196                }
1197               if (varcode == LM_TC_TEXTRM) {
1198                   mathcursor->Insert(c, LM_TC_TEXTRM);
1199               } else
1200               if (was_macro)
1201                 mathcursor->MacroModeClose();
1202               else 
1203               if (sp) {
1204                  int isp = (sp->GetSpace()<5) ? sp->GetSpace()+1: 0;
1205                  sp->SetSpace(isp);
1206                  space_on = true;
1207               } else {
1208                   if (!mathcursor->Pop() && mathcursor->IsEnd()) 
1209                     result = FINISHED;
1210               }
1211            } else
1212            if (c == '\'') {
1213               mathcursor->Insert (c, LM_TC_VAR);
1214            } else
1215            if (c == '\\') {
1216               if (was_macro)
1217                 mathcursor->MacroModeClose();
1218               bv->owner()->getMiniBuffer()->Set(_("TeX mode")); 
1219                mathcursor->setLastCode(LM_TC_TEX);
1220            } 
1221          UpdateLocal(bv);
1222       } else {
1223         // lyxerr << "Closed by action " << action << endl;
1224         result =  FINISHED;
1225       }
1226    }
1227    if (was_macro != mathcursor->InMacroMode()
1228        && action >= 0
1229        && action != LFUN_BACKSPACE)
1230            UpdateLocal(bv);
1231    if (sp && !space_on) sp = 0;
1232    if (mathcursor->Selection() || was_selection)
1233        ToggleInsetSelection(bv);
1234     
1235    if ((result == DISPATCHED) || (result == DISPATCHED_NOUPDATE))
1236       ShowInsetCursor(bv);
1237    else
1238       bv->unlockInset(this);
1239     
1240    return result;
1241 }
1242
1243
1244 void
1245 MathFuncInset::draw(Painter & pain, int x, int y)
1246
1247         if (!name.empty() && name[0] > ' ') {
1248                 LyXFont font = WhichFont(LM_TC_TEXTRM, size);
1249                 font.setLatex(LyXFont::ON);
1250                 x += (lyxfont::width('I', font) + 3) / 4;
1251                 pain.text(x, y, name, font);
1252         }
1253 }
1254
1255
1256 void MathFuncInset::Metrics() 
1257 {
1258         //ln = (name) ? strlen(name): 0;
1259         LyXFont  font = WhichFont(LM_TC_TEXTRM, size);
1260         font.setLatex(LyXFont::ON);
1261         if (name.empty()) {
1262                 width = df_width;
1263                 descent = df_des;
1264                 ascent = df_asc;
1265         } else {
1266                 width = lyxfont::width(name, font)
1267                         + lyxfont::width('I', font) / 2;
1268                 mathed_string_height(LM_TC_TEXTRM, size, name, ascent, descent);
1269         }
1270 }
1271
1272
1273 static
1274 void mathedValidate(LaTeXFeatures & features, MathParInset * par)
1275 {
1276     MathedIter it(par->GetData());
1277     
1278     while (it.OK() && !(features.binom && features.boldsymbol)) {
1279         if (it.IsInset()) {
1280             if(it.IsActive()) {
1281                 MathParInset * p = it.GetActiveInset();
1282                 if (!features.binom && p->GetType() == LM_OT_MACRO && 
1283                     p->GetName() == "binom") {
1284                     features.binom = true;
1285                 } else {
1286                     for (int i = 0; i <= p->getMaxArgumentIdx(); ++i) {
1287                         p->setArgumentIdx(i);
1288                         mathedValidate(features, p);
1289                     }
1290                 }
1291             } else {
1292                 MathedInset* p = it.GetInset();
1293                 if (!features.boldsymbol &&
1294                     p->GetName() == "boldsymbol") {
1295                     features.boldsymbol = true;
1296                 }
1297             }       
1298         }
1299         it.Next();
1300     }
1301 }