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