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