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