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