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