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