]> git.lyx.org Git - lyx.git/blob - src/mathed/formula.C
my changes during the holidyas...i expect some compilers to have some problems, but...
[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 #include "support/LOstream.h"
42 #include "LyXView.h"
43
44 extern void UpdateInset(Inset * inset, bool mark_dirty = true);
45 extern void LockedInsetStoreUndo(Undo::undo_kind);
46 extern void ShowLockedInsetCursor(long, long, int, int);
47 extern void HideLockedInsetCursor(long, long, int, int);
48 extern void FitLockedInsetCursor(long, long, int, int);
49 extern int LockInset(UpdatableInset *);
50 extern int UnlockInset(UpdatableInset *);
51
52
53 extern GC canvasGC, mathGC, mathLineGC, latexGC, cursorGC, mathFrameGC;
54 extern char * mathed_label;
55
56 extern int mono_video;
57 extern int fast_selection;
58
59 extern BufferView * current_view;
60 extern BufferList bufferlist;
61 extern char const * latex_special_chars;
62
63 short greek_kb_flag = 0;
64
65 LyXFont * Math_Fonts = 0; // this is only used by Whichfont and mathed_init_fonts (Lgb)
66
67 static LyXFont::FONT_SIZE lfont_size = LyXFont::SIZE_NORMAL;
68
69 // local global 
70 static int sel_x, sel_y;
71 static bool sel_flag;
72 MathedCursor * InsetFormula::mathcursor = 0; 
73
74
75 int MathedInset::df_asc;
76 int MathedInset::df_des;
77 int MathedInset::df_width;
78
79
80 inline bool IsMacro(short token, int id)
81 {
82    return (token != LM_TK_FRAC && token != LM_TK_SQRT &&
83           !((token == LM_TK_SYM || token == LM_TC_BSYM) && id < 255));
84 }
85
86
87 static
88 void mathedValidate(LaTeXFeatures & features, MathParInset * par);
89
90
91 LyXFont WhichFont(short type, int size)
92 {
93     LyXFont f;
94     
95       if (!Math_Fonts)
96         mathed_init_fonts();
97    
98    switch (type) {
99     case LM_TC_SYMB:         
100       f = Math_Fonts[2];
101       break;
102     case LM_TC_BSYM:         
103       f = Math_Fonts[2];
104       break;
105     case LM_TC_VAR:
106     case LM_TC_IT:
107       f = Math_Fonts[0];
108       break;
109     case LM_TC_BF:
110       f = Math_Fonts[3];
111       break;
112     case LM_TC_SF:
113       f = Math_Fonts[7];
114       break;
115     case LM_TC_CAL:
116       f = Math_Fonts[4];
117       break;
118     case LM_TC_TT:
119       f = Math_Fonts[5];
120       break;
121     case LM_TC_SPECIAL: //f = Math_Fonts[0]; break;
122     case LM_TC_TEXTRM:
123     case LM_TC_RM:    
124       f = Math_Fonts[6];
125       break;
126     default:
127       f = Math_Fonts[1];
128       break;   
129    }
130     
131     f.setSize(lfont_size);
132     
133     switch (size) {
134      case LM_ST_DISPLAY:     
135         if (type == LM_TC_BSYM) {
136             f.incSize();
137             f.incSize();
138         }
139         break;
140      case LM_ST_TEXT:
141         break;
142      case LM_ST_SCRIPT:
143         f.decSize();
144         break;
145      case LM_ST_SCRIPTSCRIPT:
146         f.decSize();
147         f.decSize();
148         break;
149      default:
150              lyxerr << "Mathed Error: wrong font size: " << size << endl;
151         break;
152     }
153     
154     if (type != LM_TC_TEXTRM) 
155       f.setColor(LyXFont::MATH);
156     return f;
157 }
158
159
160 void mathed_init_fonts() //removed 'static' because DEC cxx does not
161                          //like it (JMarc)
162         // Probably because this func is declared as a friend in math_defs.h
163         // Lgb
164 {
165
166     Math_Fonts = new LyXFont[8]; //DEC cxx cannot initialize all fonts
167                                  //at once (JMarc) rc
168     for (int i = 0 ; i < 8 ; ++i){ 
169         Math_Fonts[i] = LyXFont::ALL_SANE;
170     }
171     Math_Fonts[0].setShape(LyXFont::ITALIC_SHAPE);
172     
173     Math_Fonts[1].setFamily(LyXFont::SYMBOL_FAMILY);
174     
175     Math_Fonts[2].setFamily(LyXFont::SYMBOL_FAMILY);
176     Math_Fonts[2].setShape(LyXFont::ITALIC_SHAPE);
177
178     Math_Fonts[3].setSeries(LyXFont::BOLD_SERIES);
179       
180     Math_Fonts[4].setFamily(LyXFont::SANS_FAMILY);
181     Math_Fonts[4].setShape(LyXFont::ITALIC_SHAPE);
182       
183     Math_Fonts[5].setFamily(LyXFont::TYPEWRITER_FAMILY);
184
185     Math_Fonts[6].setFamily(LyXFont::ROMAN_FAMILY);
186
187     Math_Fonts[7].setFamily(LyXFont::SANS_FAMILY);
188     
189     LyXFont f = WhichFont(LM_TC_VAR, LM_ST_TEXT);
190     MathedInset::df_asc = f.maxAscent(); 
191     MathedInset::df_des = f.maxDescent();
192     MathedInset::df_width = f.width('I');    
193 }
194
195
196 void mathed_set_font(short type, int size)
197 {
198     if (!canvasGC) {
199             cursorGC = getGC(gc_thin_on_off_line);
200             canvasGC = getGC(gc_lighted);
201             latexGC =  getGC(gc_latex);
202             mathLineGC = getGC(gc_math);
203             mathFrameGC = getGC(gc_math_frame);
204     }
205     LyXFont f = WhichFont(type, size); 
206     if (type == LM_TC_TEX) {
207         f.setLatex(LyXFont::ON);
208         latexGC = f.getGC();
209     } else
210       mathGC = f.getGC();
211 }
212
213
214 int mathed_string_width(short type, int size, byte const * s, int ls)
215 {
216     LyXFont f = WhichFont(type, size);
217
218     byte sx[80];
219     if (MathIsBinary(type)) {
220         byte * ps = &sx[0];
221         for (int i = 0; i < ls && i < 75; ++i) {
222             *(ps++) = ' ';
223             *(ps++) = s[i];
224             *(ps++) = ' ';
225         }
226         *(ps++) = '\0';
227         ls *= 3;
228         s = &sx[0];
229     }
230     return f.textWidth(reinterpret_cast<char const *>(s), ls);
231 }
232
233
234 int mathed_char_width(short type, int size, byte c)
235 {
236     int t = (MathIsBinary(type)) ? mathed_string_width(type, size, &c, 1):
237            WhichFont(type, size).width(c);
238     return t;
239 }
240
241
242 int mathed_string_height(short type, int size, byte const * s,
243                          int ls, int & asc, int & des)
244 {
245    LyXFont font = WhichFont(type, size);
246    asc = des = 0;
247    for (int i = 0; i < ls; ++i) {
248       if (font.descent(s[i]) > des)
249         des = font.descent(s[i]);
250       if (font.ascent(s[i]) > asc)
251         asc = font.ascent(s[i]);
252    }
253    return asc + des;
254 }
255
256
257 int mathed_char_height(short type, int size, byte c, int & asc, int & des)
258 {
259    LyXFont font = WhichFont(type, size);
260    asc = des = 0;
261    des = font.descent(c);
262    asc = font.ascent(c);
263    return asc + des;
264 }
265
266
267 // In a near future maybe we use a better fonts renderer
268 void MathedInset::drawStr(short type, int siz, int x, int y, byte * s, int ls)
269 {
270     mathed_set_font(type, siz);
271     byte sx[80];
272     if (MathIsBinary(type)) {
273         byte * ps = &sx[0];
274         for (int i = 0; i < ls && i < 75; ++i) {
275             *(ps++) = ' ';
276             *(ps++) = s[i];
277             *(ps++) = ' ';
278         }
279         //    *ps = ' ';
280         ls *= 3;
281         s = &sx[0];
282     }
283     GC gc = (type == LM_TC_TEX) ? latexGC: mathGC;
284     XDrawString(fl_display, pm, gc, x, y, reinterpret_cast<char*>(s), ls);
285     XFlush(fl_display);
286 }
287
288
289 InsetFormula::InsetFormula(bool display)
290 {
291   par = new MathParInset; // this leaks
292   //   mathcursor = 0;
293   disp_flag = display;
294   //label = 0;
295   if (disp_flag) {
296     par->SetType(LM_OT_PAR);
297     par->SetStyle(LM_ST_DISPLAY);
298   }
299 }
300
301
302 InsetFormula::InsetFormula(MathParInset * p)
303 {
304    par = (p->GetType()>= LM_OT_MPAR) ? 
305          new MathMatrixInset(static_cast<MathMatrixInset*>(p)): 
306          new MathParInset(p);
307 //   mathcursor = 0;
308    
309    disp_flag = (par->GetType()>0);
310    //label = 0;
311 }
312
313
314 InsetFormula::~InsetFormula()
315 {
316    delete par;
317 }
318
319
320 Inset * InsetFormula::Clone() const
321 {
322     InsetFormula * f = new InsetFormula(par);
323     f->label = label;
324     return f;
325 }
326
327
328 void InsetFormula::Write(ostream & os)
329 {
330         os << "Formula ";
331         Latex(os, 0);
332 }
333
334
335 int InsetFormula::Latex(ostream & os, signed char fragile)
336 {
337     int ret = 0;      
338 //#warning Alejandro, the number of lines is not returned in this case
339 // This problem will disapear at 0.13.
340     string output;
341     InsetFormula::Latex(output, fragile);
342     os << output;
343     return ret;
344 }
345
346
347 int InsetFormula::Latex(string & file, signed char fragile)
348 {
349     int ret = 0;
350 //#warning Alejandro, the number of lines is not returned in this case
351 // This problem will disapear at 0.13.
352     if (fragile < 0)
353         par->Write(file);
354     else
355         mathed_write(par, file, &ret, fragile, label.c_str());
356     return ret;
357 }
358
359
360 int InsetFormula::Linuxdoc(string &/*file*/)
361 {
362     return 0;
363 }
364
365
366 int InsetFormula::DocBook(string &/*file*/)
367 {
368     return 0;
369 }
370
371
372 // Check if uses AMS macros 
373 void InsetFormula::Validate(LaTeXFeatures & features) const
374 {
375     // Validation only necesary if not using an AMS Style
376     if (!features.amsstyle)
377       mathedValidate(features, par);
378 }
379
380
381 void InsetFormula::Read(LyXLex & lex)
382 {
383         istream & is = lex.getStream();
384     
385         mathed_parser_file(is, lex.GetLineNo());   
386    
387         // Silly hack to read labels. 
388         mathed_label = 0;
389         mathed_parse(0, 0, &par);
390         par->Metrics();
391         disp_flag = (par->GetType() > 0);
392         
393         // Update line number
394         lex.setLineNo(mathed_parser_lineno());
395         
396         if (mathed_label) {
397                 label = mathed_label;
398                 mathed_label = 0;
399         }
400    
401 #ifdef DEBUG
402         Write(lyxerr);
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 = static_cast<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           current_view->owner()->getMiniBuffer()->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          current_view->owner()->getMiniBuffer()->Set(_("Math greek keyboard on"));
885        else
886          current_view->owner()->getMiniBuffer()->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        current_view->owner()->getMiniBuffer()->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              current_view->owner()->getMiniBuffer()->Set(_("No number"));  
917           } else {
918              type++;
919              current_view->owner()->getMiniBuffer()->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           pair<bool, string>
1050                 result = askForText(_("Enter new label to insert:"));
1051           if (result.first) {
1052              lb = result.second;
1053           }
1054        }
1055        if (!lb.empty() && lb[0] > ' ') {
1056           SetNumber(true);
1057           if (par->GetType() == LM_OT_MPARN) {
1058               mathcursor->setLabel(lb.c_str());
1059 //            MathMatrixInset *mt = (MathMatrixInset*)par;
1060 //            mt->SetLabel(lb);
1061           } else {
1062                   //if (label.notEmpty()) delete label;
1063               label = lb;
1064           }
1065           UpdateLocal();
1066        } else
1067                label.clear();
1068        break;
1069     }
1070     
1071     case LFUN_MATH_DISPLAY:
1072             //LockedInsetStoreUndo(Undo::INSERT);
1073             LockedInsetStoreUndo(Undo::EDIT);
1074       display(!disp_flag);
1075       UpdateLocal();
1076       break;
1077       
1078     // Invalid actions under math mode
1079     case LFUN_MATH_MODE:  
1080     {
1081         if (mathcursor->getLastCode()!= LM_TC_TEXTRM) {
1082             current_view->owner()->getMiniBuffer()->Set(_("math text mode"));
1083             varcode = LM_TC_TEXTRM;
1084         } else {
1085             varcode = LM_TC_VAR;
1086         }
1087         mathcursor->setLastCode(varcode);
1088         break; 
1089     }
1090     case LFUN_UNDO:
1091       current_view->owner()->getMiniBuffer()->Set(_("Invalid action in math mode!"));
1092       break;
1093
1094     //------- dummy actions
1095     case LFUN_EXEC_COMMAND:
1096        current_view->owner()->getMiniBuffer()->ExecCommand(); 
1097        break;
1098        
1099     default:
1100       if ((action == -1  || action == LFUN_SELFINSERT) && arg)  {
1101          unsigned char c = arg[0];
1102          LockedInsetStoreUndo(Undo::INSERT);
1103          
1104          if (c == ' ' && mathcursor->getAccent() == LM_hat) {
1105              c = '^';
1106              mathcursor->setAccent(0);
1107          }
1108          if (c == 0) {      // Dead key, do nothing 
1109              //lyxerr << "deadkey" << endl;
1110              break;
1111          } 
1112          if (isalpha(c)) {
1113              if (mathcursor->getLastCode() == LM_TC_TEX) { 
1114                mathcursor->MacroModeOpen();
1115                mathcursor->clearLastCode();
1116                varcode = LM_TC_MIN;
1117             } else          
1118             if (!varcode) {             
1119                 short f = (mathcursor->getLastCode()) ? 
1120                           mathcursor->getLastCode() :
1121                           static_cast<MathedTextCodes>(mathcursor->GetFCode());
1122                 varcode = MathIsAlphaFont(f) ?
1123                         static_cast<MathedTextCodes>(f) :
1124                         LM_TC_VAR;
1125             }
1126
1127 //           lyxerr << "Varcode << vardoce;
1128             mathcursor->Insert(c, (greek_kb_flag) ? LM_TC_SYMB: varcode);
1129             varcode = LM_TC_MIN;
1130             if (greek_kb_flag<2) greek_kb_flag = 0;
1131          } else 
1132            if (strchr("!,:;{}", c) && (varcode == LM_TC_TEX||was_macro)) {
1133                mathcursor->Insert(c, LM_TC_TEX);
1134                if (c == '{') {
1135                    mathcursor->Insert('}', LM_TC_TEX);
1136                    mathcursor->Left();
1137                }
1138                mathcursor->clearLastCode();
1139 //             varcode = LM_TC_MIN;
1140            } else
1141            if (c == '_' && varcode == LM_TC_TEX) {
1142                mathcursor->Insert(c, LM_TC_SPECIAL);
1143                mathcursor->clearLastCode();
1144 //             varcode = LM_TC_MIN;
1145            } else
1146             if (('0'<= c && c<= '9') && (varcode == LM_TC_TEX||was_macro)) {
1147                 mathcursor->MacroModeOpen();
1148                 mathcursor->clearLastCode();
1149                 mathcursor->Insert(c, LM_TC_MIN);
1150             }
1151          else
1152            if (('0'<= c && c<= '9') || strchr(";:!|[]().,?", c)) 
1153               mathcursor->Insert(c, LM_TC_CONST);
1154          else
1155            if (strchr("+/-*<>=", c))
1156               mathcursor->Insert(c, LM_TC_BOP);
1157          else
1158            if (strchr(latex_special_chars, c) && c!= '_')
1159               mathcursor->Insert(c, LM_TC_SPECIAL);
1160          else
1161            if (c == '_' || c == '^') {
1162                char s[2];
1163                s[0] = c;
1164                s[1] = 0;
1165               mathcursor->Interpret (s);
1166            } else
1167            if (c == ' ') {          
1168                if (!varcode) {  
1169                    short f = (mathcursor->getLastCode()) ? 
1170                               mathcursor->getLastCode() :
1171                               static_cast<MathedTextCodes>(mathcursor->GetFCode());
1172                    varcode = MathIsAlphaFont(f) ?
1173                            static_cast<MathedTextCodes>(f) :
1174                            LM_TC_VAR;
1175                }
1176               if (varcode == LM_TC_TEXTRM) {
1177                   mathcursor->Insert(c, LM_TC_TEXTRM);
1178               } else
1179               if (was_macro)
1180                 mathcursor->MacroModeClose();
1181               else 
1182               if (sp) {
1183                  int isp = (sp->GetSpace()<5) ? sp->GetSpace()+1: 0;
1184                  sp->SetSpace(isp);
1185                  space_on = true;
1186               } else {
1187                   if (!mathcursor->Pop() && mathcursor->IsEnd()) 
1188                     result = false;
1189               }
1190            } else
1191            if (c == '\'') {
1192               mathcursor->Insert (c, LM_TC_VAR);
1193            } else
1194            if (c == '\\') {
1195               if (was_macro)
1196                 mathcursor->MacroModeClose();
1197               current_view->owner()->getMiniBuffer()->Set(_("TeX mode")); 
1198                mathcursor->setLastCode(LM_TC_TEX);
1199            } 
1200          UpdateLocal();
1201       } else {
1202         // lyxerr << "Closed by action " << action << endl;
1203         result =  false;
1204       }
1205    }
1206    if (was_macro != mathcursor->InMacroMode()
1207        && action >= 0
1208        && action != LFUN_BACKSPACE)
1209            UpdateLocal();
1210    if (sp && !space_on) sp = 0;
1211    if (mathcursor->Selection() || (was_selection && !(fast_selection || mono_video)))
1212        ToggleInsetSelection();
1213     
1214    if (result)
1215       ShowInsetCursor();
1216    else
1217       UnlockInset(this);
1218     
1219    return result;
1220 }
1221
1222
1223 void
1224 MathFuncInset::Draw(int x, int y)
1225
1226         if (name && name[0] > ' ') {
1227                 LyXFont  font = WhichFont(LM_TC_TEXTRM, size);
1228                 font.setLatex(LyXFont::ON);
1229                 x += (font.textWidth("I", 1)+3)/4;
1230                 if (mono_video) {
1231                         int a = font.maxAscent(), d = font.maxDescent();
1232                         XFillRectangle (fl_display, pm, getGC(gc_copy),
1233                                         x, y-a,
1234                                         font.textWidth(name, strlen(name)), a+d);
1235                         XFlush(fl_display);
1236                 }
1237                 font.drawString(name, pm, y, x);
1238         }
1239 }
1240
1241
1242 void MathFuncInset::Metrics() 
1243 {
1244         ln = (name) ? strlen(name): 0;
1245         LyXFont  font = WhichFont(LM_TC_TEXTRM, size);
1246         font.setLatex(LyXFont::ON);
1247         width = font.textWidth(name, ln) + font.textWidth("I", 1)/2;
1248         mathed_string_height(LM_TC_TEXTRM, size,
1249                              reinterpret_cast<unsigned char const *>(name),
1250                              strlen(name), ascent, descent);
1251 }
1252
1253
1254 static
1255 void mathedValidate(LaTeXFeatures & features, MathParInset * par)
1256 {
1257     MathedIter it(par->GetData());
1258     
1259     while (it.OK() && !(features.binom && features.boldsymbol)) {
1260         if (it.IsInset()) {
1261             if(it.IsActive()) {
1262                 MathParInset * p = it.GetActiveInset();
1263                 if (!features.binom && p->GetType() == LM_OT_MACRO && 
1264                     strcmp(p->GetName(), "binom") == 0) {
1265                     features.binom = true;
1266                 } else {
1267                     for (int i = 0; i <= p->getMaxArgumentIdx(); ++i) {
1268                         p->setArgumentIdx(i);
1269                         mathedValidate(features, p);
1270                     }
1271                 }
1272             } else {
1273                 MathedInset* p = it.GetInset();
1274                 if (!features.boldsymbol && p->GetName() &&
1275                     strcmp(p->GetName(), "boldsymbol") == 0) {
1276                     features.boldsymbol = true;
1277                 }
1278             }       
1279         }
1280         it.Next();
1281     }
1282 }