]> git.lyx.org Git - lyx.git/blob - src/mathed/formula.C
the fstream/iostream changes and some small other things
[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
43 extern void UpdateInset(Inset * inset, bool mark_dirty = true);
44 extern void LockedInsetStoreUndo(Undo::undo_kind);
45 extern MiniBuffer * minibuffer;
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((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     FILE * file = lex.getFile();
384     
385     mathed_parser_file(file, 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(stdout);
403    fflush(stdout);
404 #endif
405 }
406
407
408 int InsetFormula::Ascent(LyXFont const &) const
409 {
410    return par->Ascent() + ((disp_flag) ? 8 : 1);
411 }
412
413
414 int InsetFormula::Descent(LyXFont const &) const
415 {
416    return par->Descent() + ((disp_flag) ? 8 : 1);
417 }
418
419
420 int InsetFormula::Width(LyXFont const & f) const
421 {
422     lfont_size = f.size();
423     par->Metrics();
424     return par->Width(); //+2;
425 }
426
427
428 void InsetFormula::Draw(LyXFont f, LyXScreen & scr, int baseline, float & x)
429 {
430         // This is Alejandros domain so I'll use this
431         unsigned long pm = scr.getForeground();
432         
433    lfont_size = f.size();
434    mathed_set_font(LM_TC_TEXTRM, LM_ST_TEXT); // otherwise a segfault could occur
435                         // in some XDrawRectangles (i.e. matrix) (Matthias)   
436    if (mathcursor && mathcursor->GetPar() == par) { 
437        if (mathcursor->Selection()) {
438            int n;
439            XPoint * p = mathcursor->SelGetArea(n);
440            XFillPolygon(fl_display, pm, getGC(gc_selection),
441                         p, n, Nonconvex, CoordModeOrigin);
442        }
443        mathcursor->Draw(pm, int(x), baseline);
444    } else {
445 //       par->Metrics();
446        par->setDrawable(pm);
447        par->Draw(int(x), baseline);
448    }
449    x += float(Width(f));
450  
451    if (par->GetType() == LM_OT_PARN || par->GetType() == LM_OT_MPARN) {
452        char s[80];
453        LyXFont  font = WhichFont(LM_TC_BF, par->size);
454        font.setLatex(LyXFont::OFF);
455       
456        if (par->GetType() == LM_OT_PARN) {
457            if (!label.empty())
458              sprintf(s, "(%s)", label.c_str());
459            else
460              sprintf(s, "(#)");
461            font.drawString(s, pm, baseline, int(x+20));
462        } else 
463        if (par->GetType() == LM_OT_MPARN) {
464            MathMatrixInset *mt = (MathMatrixInset*)par;
465            int y;
466            MathedRowSt const* crow = mt->getRowSt();
467            while (crow) {
468                y = baseline + crow->getBaseline();
469                if (crow->isNumbered()) {
470                    if (crow->getLabel())
471                      sprintf(s, "(%s)", crow->getLabel());
472                    else
473                      sprintf(s, "(#)");
474                    font.drawString(s, pm, y, int(x+20));
475                }
476                crow = crow->getNext();
477            }
478        }
479    }
480    cursor_visible = false;
481 }
482
483
484 void InsetFormula::Edit(int x, int y)
485 {
486    mathcursor = new MathedCursor(par);
487    LockInset(this);
488    par->Metrics();
489    UpdateInset(this, false);
490    x += par->xo; 
491    y += par->yo; 
492    mathcursor->SetPos(x, y);
493     sel_x = sel_y = 0;
494     sel_flag = false;
495 }
496
497
498 void InsetFormula::InsetUnlock()
499 {
500    if (mathcursor) {
501        if (mathcursor->InMacroMode()) {
502            mathcursor->MacroModeClose();
503            UpdateLocal();
504        }                                         
505      delete mathcursor;
506    }
507    mathcursor = 0;
508    UpdateInset(this, false);
509 }
510
511
512 // Now a symbol can be inserted only if the inset is locked
513 void InsetFormula::InsertSymbol(char const * s)
514
515    if (!s || !mathcursor) return;   
516    mathcursor->Interpret(s);
517    UpdateLocal();
518 }
519
520    
521 void InsetFormula::GetCursorPos(int& x, int& y) const
522 {
523     mathcursor->GetPos(x, y);
524     x -= par->xo; 
525     y -= par->yo;
526 }
527
528 void InsetFormula::ToggleInsetCursor()
529 {
530   if (!mathcursor)
531     return;
532
533   int x, y, asc, desc;
534   mathcursor->GetPos(x, y);
535 //  x -= par->xo; 
536   y -= par->yo; 
537     LyXFont font = WhichFont(LM_TC_TEXTRM, LM_ST_TEXT);
538   asc = font.maxAscent();
539   desc = font.maxDescent();
540   
541   if (cursor_visible)
542     HideLockedInsetCursor(x, y, asc, desc);
543   else
544     ShowLockedInsetCursor(x, y, asc, desc);
545   cursor_visible = !cursor_visible;
546 }
547
548
549 void InsetFormula::ShowInsetCursor()
550 {
551   if (!cursor_visible) {
552     int x, y, asc, desc;
553     if (mathcursor) {
554       mathcursor->GetPos(x, y);
555       //  x -= par->xo; 
556       y -= par->yo;
557         LyXFont font = WhichFont(LM_TC_TEXTRM, LM_ST_TEXT);
558         asc = font.maxAscent();
559         desc = font.maxDescent();
560       FitLockedInsetCursor(x, y, asc, desc);
561     }
562     ToggleInsetCursor();
563   }
564 }
565
566
567 void InsetFormula::HideInsetCursor()
568 {
569   if (cursor_visible)
570     ToggleInsetCursor();
571 }
572
573
574 void InsetFormula::ToggleInsetSelection()
575 {
576     if (!mathcursor)
577       return;
578     
579 //    int x, y, w, h;
580     //int n;
581     //XPoint * p = 
582     //mathcursor->SelGetArea(n);
583 //    XFillPolygon(fl_display, pm, LyXGetSelectionGC(), p, n, Nonconvex, CoordModeOrigin);
584 //    x -= par->xo; 
585 //    y -= par->yo;
586
587     UpdateInset(this, false);
588       
589 }
590
591
592 void InsetFormula::display(bool dspf)
593 {
594    if (dspf != disp_flag) {
595       if (dspf) {
596          par->SetType(LM_OT_PAR);
597          par->SetStyle(LM_ST_DISPLAY);
598       } else {
599          if (par->GetType() >= LM_OT_MPAR) { 
600             MathParInset * p = new MathParInset(par);
601             delete par;
602             par = p;
603             if (mathcursor) 
604                mathcursor->SetPar(par); 
605          }
606          par->SetType(LM_OT_MIN);
607          par->SetStyle(LM_ST_TEXT);
608          if (!label.empty() && par->GetType() != LM_OT_MPARN) {
609                  label.clear();
610          }
611       }
612       disp_flag = dspf;
613    }
614 }
615
616
617 int InsetFormula::GetNumberOfLabels() const
618 {
619    // This is dirty, I know. I'll clean it at 0.13
620    if (par->GetType() == LM_OT_MPARN) {
621        MathMatrixInset * mt = static_cast<MathMatrixInset*>(par);
622        int nl = 0;
623        MathedRowSt const * crow = mt->getRowSt();
624        while (crow) {
625            if (crow->getLabel()) ++nl;
626            crow = crow->getNext();
627        }
628        return nl;
629    } else
630    if (!label.empty())
631        return 1;
632    else
633        return 0;
634 }
635
636
637 string InsetFormula::getLabel(int il) const
638 {
639 //#warning This is dirty, I know. Ill clean it at 0.11
640         // Correction, the only way to clean this is with a new kernel: 0.13.
641         if (par->GetType() == LM_OT_MPARN) {
642                 string lab;
643                 MathMatrixInset * mt = static_cast<MathMatrixInset*>(par);
644                 int nl = 0;
645                 MathedRowSt const * crow = mt->getRowSt();
646                 while (crow) {
647                         if (crow->getLabel()) {
648                                 if (nl == il) {
649                                         lab = crow->getLabel();
650                                         break;
651                                 }
652                                 ++nl;
653                         }
654                         crow = crow->getNext();
655                 }
656                 return lab;
657         }
658         return label;
659 }
660
661
662 void InsetFormula::UpdateLocal()
663 {
664    par->Metrics();  // To inform lyx kernel the exact size 
665                   // (there were problems with arrays).
666    UpdateInset(this);
667 }
668
669
670 void InsetFormula::InsetButtonRelease(int x, int y, int /*button*/)
671 {
672     HideInsetCursor();
673     x += par->xo;
674     y += par->yo;
675     mathcursor->SetPos(x, y);
676     ShowInsetCursor();
677     if (sel_flag) {
678         sel_flag = false; 
679         sel_x = sel_y = 0;
680         UpdateInset(this, false); 
681     }
682 }
683
684
685 void InsetFormula::InsetButtonPress(int x, int y, int /*button*/)
686 {
687     sel_flag = false;
688     sel_x = x;  sel_y = y; 
689     if (mathcursor->Selection()) {
690         mathcursor->SelClear();
691         UpdateInset(this, false); 
692     }
693 }
694
695
696 void InsetFormula::InsetMotionNotify(int x, int y, int /*button*/)
697 {
698     if (sel_x && sel_y && abs(x-sel_x) > 4 && !sel_flag) {
699         sel_flag = true;
700         HideInsetCursor();
701         mathcursor->SetPos(sel_x + par->xo, sel_y + par->yo);
702         mathcursor->SelStart();
703         ShowInsetCursor(); 
704         mathcursor->GetPos(sel_x, sel_y);
705     } else
706       if (sel_flag) {
707           HideInsetCursor();
708           x += par->xo;
709           y += par->yo;
710           mathcursor->SetPos(x, y);
711           ShowInsetCursor();
712           mathcursor->GetPos(x, y);
713           if (sel_x!= x || sel_y!= y)
714             UpdateInset(this, false); 
715           sel_x = x;  sel_y = y;
716       }
717 }
718
719
720 void InsetFormula::InsetKeyPress(XKeyEvent *)
721 {
722         lyxerr[Debug::MATHED] << "Used InsetFormula::InsetKeyPress." << endl;
723 }
724
725
726 // Special Mathed functions
727 bool InsetFormula::SetNumber(bool numbf)
728 {
729    if (disp_flag) {
730       short type = par->GetType();
731       bool oldf = (type == LM_OT_PARN || type == LM_OT_MPARN);
732       if (numbf && !oldf) ++type;
733       if (!numbf && oldf) --type;
734       par->SetType(type);
735       return oldf;
736    } else
737      return false;
738 }
739
740
741 bool InsetFormula::LocalDispatch(int action, char const * arg)
742 {
743 //   extern char *dispatch_result;
744     MathedTextCodes varcode = LM_TC_MIN;       
745    bool was_macro = mathcursor->InMacroMode();
746    bool sel = false;
747    bool space_on = false;
748    bool was_selection = mathcursor->Selection();
749    bool result = true;
750    static MathSpaceInset * sp= 0;
751
752    HideInsetCursor();
753    if (mathcursor->Selection() && (fast_selection || mono_video))
754            ToggleInsetSelection();
755
756     if (mathcursor->getLastCode() == LM_TC_TEX) { 
757         varcode = LM_TC_TEX;
758     }
759    switch (action) {
760        
761     // --- Cursor Movements ---------------------------------------------
762     case LFUN_RIGHTSEL: sel = true;
763     case LFUN_RIGHT:
764       {
765          result = mathcursor->Right(sel);
766          break;
767       }
768     case LFUN_LEFTSEL: sel = true;     
769     case LFUN_LEFT:
770       {
771          result = mathcursor->Left(sel);
772          break;
773       }
774     case LFUN_UPSEL: sel = true;  
775     case LFUN_UP:
776       result = mathcursor->Up(sel);
777       break;
778        
779     case LFUN_DOWNSEL: sel = true;  
780     case LFUN_DOWN:
781       result = mathcursor->Down(sel);
782       break;
783     case LFUN_HOME:
784       mathcursor->Home();
785       break;
786     case LFUN_END:
787       mathcursor->End();
788       break;
789     case LFUN_DELETE_LINE_FORWARD:
790             //LockedInsetStoreUndo(Undo::INSERT);
791             LockedInsetStoreUndo(Undo::DELETE);
792       mathcursor->DelLine();
793       UpdateLocal();
794       break;
795     case LFUN_BREAKLINE:
796       LockedInsetStoreUndo(Undo::INSERT);
797       mathcursor->Insert(' ', LM_TC_CR);
798       par = mathcursor->GetPar();
799       UpdateLocal();     
800       break;
801     case LFUN_TAB:
802       LockedInsetStoreUndo(Undo::INSERT);
803       mathcursor->Insert(0, LM_TC_TAB);
804       //UpdateInset(this);
805       break;     
806     case LFUN_TABINSERT:
807       LockedInsetStoreUndo(Undo::INSERT);
808       mathcursor->Insert('T', LM_TC_TAB);
809       UpdateLocal();
810       break;     
811     case LFUN_BACKSPACE:
812        if (!mathcursor->Left()) 
813          break;
814        
815        if (!mathcursor->InMacroMode() && mathcursor->pullArg()) {       
816            UpdateInset(this);
817            break;
818        }
819       
820     case LFUN_DELETE:
821             //LockedInsetStoreUndo(Undo::INSERT);
822             LockedInsetStoreUndo(Undo::DELETE);
823       mathcursor->Delete();       
824       UpdateInset(this);
825       break;    
826 //    case LFUN_GETXY:
827 //      sprintf(dispatch_buffer, "%d %d",);
828 //      dispatch_result = dispatch_buffer;
829 //      break;
830     case LFUN_SETXY:
831       {
832          int x, y, x1, y1;
833          sscanf(arg, "%d %d", &x, &y);
834          par->GetXY(x1, y1);
835          mathcursor->SetPos(x1+x, y1+y);
836       }
837       break;
838
839       /* cursor selection ---------------------------- */
840
841     case LFUN_PASTE:
842             if (was_macro)
843                 mathcursor->MacroModeClose();
844             LockedInsetStoreUndo(Undo::INSERT);
845             mathcursor->SelPaste(); UpdateLocal(); break;
846     case LFUN_CUT:
847             LockedInsetStoreUndo(Undo::DELETE);
848             mathcursor->SelCut(); UpdateLocal(); break;
849     case LFUN_COPY: mathcursor->SelCopy(); break;      
850     case LFUN_HOMESEL:
851     case LFUN_ENDSEL:
852     case LFUN_WORDRIGHTSEL:
853     case LFUN_WORDLEFTSEL:
854       break;
855       
856     // --- accented characters ------------------------------
857
858     case LFUN_UMLAUT: mathcursor->setAccent(LM_ddot); break;
859     case LFUN_CIRCUMFLEX: mathcursor->setAccent(LM_hat); break;
860     case LFUN_GRAVE: mathcursor->setAccent(LM_grave); break;
861     case LFUN_ACUTE: mathcursor->setAccent(LM_acute); break;
862     case LFUN_TILDE: mathcursor->setAccent(LM_tilde); break;
863     case LFUN_MACRON: mathcursor->setAccent(LM_bar); break;
864     case LFUN_DOT: mathcursor->setAccent(LM_dot); break;
865     case LFUN_CARON: mathcursor->setAccent(LM_check); break;
866     case LFUN_BREVE: mathcursor->setAccent(LM_breve); break;
867     case LFUN_VECTOR: mathcursor->setAccent(LM_vec); break; 
868       
869     // Greek mode     
870     case LFUN_GREEK:
871     {
872        if (!greek_kb_flag) {
873           greek_kb_flag = 1;
874           minibuffer->Set(_("Math greek mode on"));
875        } else
876          greek_kb_flag = 0;
877        break;
878     }  
879       
880     // Greek keyboard      
881     case LFUN_GREEK_TOGGLE:
882     {
883        greek_kb_flag = (greek_kb_flag) ? 0 : 2;
884        if (greek_kb_flag)
885          minibuffer->Set(_("Math greek keyboard on"));
886        else
887          minibuffer->Set(_("Math greek keyboard off"));
888        break;
889     }  
890    
891       //  Math fonts 
892     case LFUN_BOLD:     mathcursor->setLastCode(LM_TC_BF); break;
893     case LFUN_SANS:  mathcursor->setLastCode( LM_TC_SF); break;
894     case LFUN_EMPH:  mathcursor->setLastCode(LM_TC_CAL); break;
895     case LFUN_ROMAN: mathcursor->setLastCode(LM_TC_RM); break;
896     case LFUN_CODE: mathcursor->setLastCode(LM_TC_TT); break;   
897     case LFUN_DEFAULT:  mathcursor->setLastCode(LM_TC_VAR ) ; break;
898     case LFUN_TEX: 
899     {
900 //       varcode = LM_TC_TEX;
901         mathcursor->setLastCode(LM_TC_TEX);
902        minibuffer->Set(_("TeX mode")); 
903        break;
904     }
905
906     case LFUN_MATH_NUMBER:
907     {
908       LockedInsetStoreUndo(Undo::INSERT);
909        if (disp_flag) {
910           short type = par->GetType();
911           bool oldf = (type == LM_OT_PARN || type == LM_OT_MPARN);
912           if (oldf) {
913              type--;
914              if (!label.empty()) {
915                      label.clear();
916              }
917              minibuffer->Set(_("No number"));  
918           } else {
919              type++;
920              minibuffer->Set(_("Number"));
921           }
922           par->SetType(type);
923           UpdateLocal();
924        }
925        break;
926     }
927     
928     case LFUN_MATH_NONUMBER:
929     { 
930         if (par->GetType() == LM_OT_MPARN) {
931 //         MathMatrixInset *mt = (MathMatrixInset*)par;
932            //BUG 
933 //         mt->SetNumbered(!mt->IsNumbered());
934             
935             mathcursor->setNumbered();
936            UpdateLocal();
937         }
938         break;
939     }
940        
941     case LFUN_MATH_LIMITS:
942     {
943       LockedInsetStoreUndo(Undo::INSERT);
944        if (mathcursor->Limits())
945          UpdateLocal();
946     }
947  
948     case LFUN_MATH_SIZE:
949        if (arg) {
950            latexkeys * l = in_word_set (arg, strlen(arg));
951            int sz = (l) ? l->id: -1;
952            mathcursor->SetSize(sz);
953            UpdateLocal();
954            break;
955        }
956        
957     case LFUN_INSERT_MATH:
958     {
959         LockedInsetStoreUndo(Undo::INSERT);
960         InsertSymbol(arg);
961         break;
962     }
963     
964     case LFUN_INSERT_MATRIX:
965     { 
966       LockedInsetStoreUndo(Undo::INSERT);
967        int k, m, n;
968        char s[80], arg2[80];
969        // This is just so that too long args won't ooze out of s.
970        strncpy(arg2, arg, 80); arg2[79]= '\0';
971        k = sscanf(arg2, "%d %d %s", &m, &n, s);
972        s[79] = '\0';
973         
974        if (k < 1) {
975            m = n = 1;
976        } else if (k == 1) {
977            n = 1;
978        }
979         
980        MathMatrixInset * p = new MathMatrixInset(m, n);      
981        if (mathcursor && p) {
982           if (k > 2 && int(strlen(s)) > m)
983             p->SetAlign(s[0], &s[1]);
984           mathcursor->Insert(p, LM_TC_ACTIVE_INSET);
985           UpdateLocal();
986        }
987        break;
988     }
989       
990     case LFUN_MATH_DELIM:
991     {  
992       LockedInsetStoreUndo(Undo::INSERT);
993        char lf[40], rg[40], arg2[40];
994        int ilf = '(', irg = '.';
995        latexkeys * l;
996        string vdelim("(){}[]./|");
997         
998        if (!arg) break;
999        strncpy(arg2, arg, 40); arg2[39]= '\0';
1000        int n = sscanf(arg2, "%s %s", lf, rg);
1001        lf[39] = '\0'; rg[39] = '\0';
1002
1003        if (n > 0) {
1004            if (isdigit(lf[0])) 
1005              ilf = atoi(lf);
1006            else 
1007              if (lf[1]) {
1008                  l = in_word_set(lf, strlen(lf));
1009                  // Long words will cause l == 0; so check.
1010                  if(l) ilf = l->id;
1011              } else
1012              if (vdelim.find(lf[0]) != string::npos)
1013                ilf = lf[0];
1014            
1015            if (n > 1) {
1016                if (isdigit(rg[0]))
1017                  irg = atoi(rg);
1018                else 
1019                  if (rg[1]) {
1020                      l = in_word_set(rg, strlen(rg));
1021                      if(l) irg = l->id;
1022                  } else
1023                  if (vdelim.find(rg[0]) != string::npos)
1024                    irg = rg[0];
1025            }
1026        }
1027        
1028        MathDelimInset * p = new MathDelimInset(ilf, irg);
1029        mathcursor->Insert(p, LM_TC_ACTIVE_INSET);
1030        UpdateLocal();                             
1031        break;
1032     }
1033
1034     case LFUN_PROTECTEDSPACE:
1035     {
1036       LockedInsetStoreUndo(Undo::INSERT);
1037        sp = new MathSpaceInset(1); 
1038        mathcursor->Insert(sp);
1039        space_on = true;
1040        UpdateLocal();
1041        break;
1042     }
1043       
1044     case LFUN_INSERT_LABEL:
1045     {
1046       LockedInsetStoreUndo(Undo::INSERT);
1047        if (par->GetType() < LM_OT_PAR) break;
1048        string lb = arg;
1049        if (lb.empty())
1050               lb = string(askForText(_("Enter new label to insert:")));
1051        if (!lb.empty() && lb[0] > ' ') {
1052           SetNumber(true);
1053           if (par->GetType() == LM_OT_MPARN) {
1054               mathcursor->setLabel(lb.c_str());
1055 //            MathMatrixInset *mt = (MathMatrixInset*)par;
1056 //            mt->SetLabel(lb);
1057           } else {
1058                   //if (label.notEmpty()) delete label;
1059               label = lb;
1060           }
1061           UpdateLocal();
1062        } else
1063                label.clear();
1064        break;
1065     }
1066     
1067     case LFUN_MATH_DISPLAY:
1068             //LockedInsetStoreUndo(Undo::INSERT);
1069             LockedInsetStoreUndo(Undo::EDIT);
1070       display(!disp_flag);
1071       UpdateLocal();
1072       break;
1073       
1074     // Invalid actions under math mode
1075     case LFUN_MATH_MODE:  
1076     {
1077         if (mathcursor->getLastCode()!= LM_TC_TEXTRM) {
1078             minibuffer->Set(_("math text mode"));
1079             varcode = LM_TC_TEXTRM;
1080         } else {
1081             varcode = LM_TC_VAR;
1082         }
1083         mathcursor->setLastCode(varcode);
1084         break; 
1085     }
1086     case LFUN_UNDO:
1087       minibuffer->Set(_("Invalid action in math mode!"));
1088       break;
1089
1090     //------- dummy actions
1091     case LFUN_EXEC_COMMAND:
1092        minibuffer->ExecCommand(); 
1093        break;
1094        
1095     default:
1096       if ((action == -1  || action == LFUN_SELFINSERT) && arg)  {
1097          unsigned char c = arg[0];
1098          LockedInsetStoreUndo(Undo::INSERT);
1099          
1100          if (c == ' ' && mathcursor->getAccent() == LM_hat) {
1101              c = '^';
1102              mathcursor->setAccent(0);
1103          }
1104          if (c == 0) {      // Dead key, do nothing 
1105              //lyxerr << "deadkey" << endl;
1106              break;
1107          } 
1108          if (isalpha(c)) {
1109              if (mathcursor->getLastCode() == LM_TC_TEX) { 
1110                mathcursor->MacroModeOpen();
1111                mathcursor->clearLastCode();
1112                varcode = LM_TC_MIN;
1113             } else          
1114             if (!varcode) {             
1115                 short f = (mathcursor->getLastCode()) ? 
1116                           mathcursor->getLastCode():
1117                           (MathedTextCodes)mathcursor->GetFCode();
1118                varcode =  MathIsAlphaFont(f) ?  (MathedTextCodes)f:LM_TC_VAR;
1119             }
1120
1121 //           lyxerr << "Varcode << vardoce;
1122             mathcursor->Insert(c, (greek_kb_flag) ? LM_TC_SYMB: varcode);
1123             varcode = LM_TC_MIN;
1124             if (greek_kb_flag<2) greek_kb_flag = 0;
1125          } else 
1126            if (strchr("!,:;{}", c) && (varcode == LM_TC_TEX||was_macro)) {
1127                mathcursor->Insert(c, LM_TC_TEX);
1128                if (c == '{') {
1129                    mathcursor->Insert('}', LM_TC_TEX);
1130                    mathcursor->Left();
1131                }
1132                mathcursor->clearLastCode();
1133 //             varcode = LM_TC_MIN;
1134            } else
1135            if (c == '_' && varcode == LM_TC_TEX) {
1136                mathcursor->Insert(c, LM_TC_SPECIAL);
1137                mathcursor->clearLastCode();
1138 //             varcode = LM_TC_MIN;
1139            } else
1140             if (('0'<= c && c<= '9') && (varcode == LM_TC_TEX||was_macro)) {
1141                 mathcursor->MacroModeOpen();
1142                 mathcursor->clearLastCode();
1143                 mathcursor->Insert(c, LM_TC_MIN);
1144             }
1145          else
1146            if (('0'<= c && c<= '9') || strchr(";:!|[]().,?", c)) 
1147               mathcursor->Insert(c, LM_TC_CONST);
1148          else
1149            if (strchr("+/-*<>=", c))
1150               mathcursor->Insert(c, LM_TC_BOP);
1151          else
1152            if (strchr(latex_special_chars, c) && c!= '_')
1153               mathcursor->Insert(c, LM_TC_SPECIAL);
1154          else
1155            if (c == '_' || c == '^') {
1156                char s[2];
1157                s[0] = c;
1158                s[1] = 0;
1159               mathcursor->Interpret (s);
1160            } else
1161            if (c == ' ') {          
1162                if (!varcode) {  
1163                    short f = (mathcursor->getLastCode()) ? 
1164                               mathcursor->getLastCode():
1165                               (MathedTextCodes)mathcursor->GetFCode();
1166                    varcode = MathIsAlphaFont(f) ? (MathedTextCodes)f:LM_TC_VAR;
1167                }
1168               if (varcode == LM_TC_TEXTRM) {
1169                   mathcursor->Insert(c, LM_TC_TEXTRM);
1170               } else
1171               if (was_macro)
1172                 mathcursor->MacroModeClose();
1173               else 
1174               if (sp) {
1175                  int isp = (sp->GetSpace()<5) ? sp->GetSpace()+1: 0;
1176                  sp->SetSpace(isp);
1177                  space_on = true;
1178               } else {
1179                   if (!mathcursor->Pop() && mathcursor->IsEnd()) 
1180                     result = false;
1181               }
1182            } else
1183            if (c == '\'') {
1184               mathcursor->Insert (c, LM_TC_VAR);
1185            } else
1186            if (c == '\\') {
1187               if (was_macro)
1188                 mathcursor->MacroModeClose();
1189               minibuffer->Set(_("TeX mode")); 
1190                mathcursor->setLastCode(LM_TC_TEX);
1191            } 
1192          UpdateLocal();
1193       } else {
1194         // lyxerr << "Closed by action " << action << endl;
1195         result =  false;
1196       }
1197    }
1198    if (was_macro != mathcursor->InMacroMode()
1199        && action >= 0
1200        && action != LFUN_BACKSPACE)
1201            UpdateLocal();
1202    if (sp && !space_on) sp = 0;
1203    if (mathcursor->Selection() || (was_selection && !(fast_selection || mono_video)))
1204        ToggleInsetSelection();
1205     
1206    if (result)
1207       ShowInsetCursor();
1208    else
1209       UnlockInset(this);
1210     
1211    return result;
1212 }
1213
1214
1215 void
1216 MathFuncInset::Draw(int x, int y)
1217
1218         if (name && name[0] > ' ') {
1219                 LyXFont  font = WhichFont(LM_TC_TEXTRM, size);
1220                 font.setLatex(LyXFont::ON);
1221                 x += (font.textWidth("I", 1)+3)/4;
1222                 if (mono_video) {
1223                         int a = font.maxAscent(), d = font.maxDescent();
1224                         XFillRectangle (fl_display, pm, getGC(gc_copy),
1225                                         x, y-a,
1226                                         font.textWidth(name, strlen(name)), a+d);
1227                         XFlush(fl_display);
1228                 }
1229                 font.drawString(name, pm, y, x);
1230         }
1231 }
1232
1233
1234 void MathFuncInset::Metrics() 
1235 {
1236         ln = (name) ? strlen(name): 0;
1237         LyXFont  font = WhichFont(LM_TC_TEXTRM, size);
1238         font.setLatex(LyXFont::ON);
1239         width = font.textWidth(name, ln) + font.textWidth("I", 1)/2;
1240         mathed_string_height(LM_TC_TEXTRM, size,
1241                              reinterpret_cast<unsigned char const *>(name),
1242                              strlen(name), ascent, descent);
1243 }
1244
1245
1246 static
1247 void mathedValidate(LaTeXFeatures & features, MathParInset * par)
1248 {
1249     MathedIter it(par->GetData());
1250     
1251     while (it.OK() && !(features.binom && features.boldsymbol)) {
1252         if (it.IsInset()) {
1253             if(it.IsActive()) {
1254                 MathParInset * p = it.GetActiveInset();
1255                 if (!features.binom && p->GetType() == LM_OT_MACRO && 
1256                     strcmp(p->GetName(), "binom") == 0) {
1257                     features.binom = true;
1258                 } else {
1259                     for (int i = 0; i <= p->getMaxArgumentIdx(); ++i) {
1260                         p->setArgumentIdx(i);
1261                         mathedValidate(features, p);
1262                     }
1263                 }
1264             } else {
1265                 MathedInset* p = it.GetInset();
1266                 if (!features.boldsymbol && p->GetName() &&
1267                     strcmp(p->GetName(), "boldsymbol") == 0) {
1268                     features.boldsymbol = true;
1269                 }
1270             }       
1271         }
1272         it.Next();
1273     }
1274 }