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