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