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