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