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