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