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