]> git.lyx.org Git - lyx.git/blob - src/mathed/formulabase.C
d6ad033d82916b8f1ebe5247c49b3aa4eaf2c97f
[lyx.git] / src / mathed / formulabase.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 #include <fstream>
18
19 #include "Lsstream.h"
20
21 #ifdef __GNUG__
22 #pragma implementation
23 #endif
24
25 #include "formula.h"
26 #include "formulamacro.h"
27 #include "commandtags.h"
28 #include "math_cursor.h"
29 #include "math_parser.h"
30 #include "BufferView.h"
31 #include "lyxtext.h"
32 #include "lyxfunc.h"
33 #include "gettext.h"
34 #include "LaTeXFeatures.h"
35 #include "debug.h"
36 #include "support/LOstream.h"
37 #include "LyXView.h"
38 #include "Painter.h"
39 #include "font.h"
40 #include "math_arrayinset.h"
41 #include "math_spaceinset.h"
42 #include "math_deliminset.h"
43 #include "support/lyxlib.h"
44 #include "mathed/support.h"
45 #include "undo_funcs.h"
46
47 using std::endl;
48 using std::ostream;
49 using std::vector;
50
51 extern char const * latex_special_chars;
52
53 int greek_kb_flag = 0;
54 extern char const * latex_mathenv[];
55 LyXFont           * Math_Fonts = 0;
56 MathCursor        * mathcursor = 0;
57
58
59 namespace {
60
61
62 // local global
63 int sel_x;
64 int sel_y;
65 bool sel_flag;
66
67 void mathed_init_fonts();
68
69 string nicelabel(string const & label)
70 {
71         return "(" + (label.empty() ? "#" : label) + ")";
72 }
73
74 void handleFont(BufferView * bv, MathTextCodes t) 
75 {
76         if (mathcursor->Selection())
77                 bv->lockedInsetStoreUndo(Undo::EDIT);
78         mathcursor->handleFont(t);
79 }
80
81 bool openNewInset(BufferView * bv, UpdatableInset * new_inset)
82 {
83         LyXText * lt = bv->getLyXText();
84         
85         bv->beforeChange(lt);
86         finishUndo();
87         if (!bv->insertInset(new_inset)) {
88                 delete new_inset;
89                 return false;
90         }
91         new_inset->edit(bv, 0, 0, 0);
92         return true;
93 }
94
95 } // namespaces
96
97
98
99 LyXFont WhichFont(short type, int size)
100 {
101         LyXFont f;
102         
103         if (!Math_Fonts)
104                 mathed_init_fonts();
105
106         switch (type) {
107         case LM_TC_SYMB:        
108                 f = Math_Fonts[2];
109                 break;
110
111         case LM_TC_BSYM:        
112                 f = Math_Fonts[2];
113                 break;
114
115         case LM_TC_VAR:
116         case LM_TC_IT:
117                 f = Math_Fonts[0];
118                 break;
119
120         case LM_TC_BF:
121                 f = Math_Fonts[3];
122                 break;
123
124         case LM_TC_SF:
125                 f = Math_Fonts[7];
126                 break;
127
128         case LM_TC_CAL:
129                 f = Math_Fonts[4];
130                 break;
131
132         case LM_TC_TT:
133                 f = Math_Fonts[5];
134                 break;
135
136         case LM_TC_SPECIAL: //f = Math_Fonts[0]; break;
137         case LM_TC_TEXTRM:
138         case LM_TC_RM:
139                 f = Math_Fonts[6];
140                 break;
141
142         default:
143                 f = Math_Fonts[1];
144                 break;
145         }
146
147         switch (size) {
148         case LM_ST_DISPLAY:
149                 if (type == LM_TC_BSYM) {
150                         f.incSize();
151                         f.incSize();
152                 }
153                 break;
154
155         case LM_ST_TEXT:
156                 break;
157
158         case LM_ST_SCRIPT:
159                 f.decSize();
160                 break;
161
162         case LM_ST_SCRIPTSCRIPT:
163                 f.decSize();
164                 f.decSize();
165                 break;
166
167         default:
168                 lyxerr << "Math Error: wrong font size: " << size << endl;
169                 break;
170         }
171
172         if (type != LM_TC_TEXTRM)
173                 f.setColor(LColor::math);
174
175         return f;
176 }
177
178
179 namespace {
180
181 void mathed_init_fonts()
182 {
183         Math_Fonts = new LyXFont[8]; //DEC cxx cannot initialize all fonts
184         //at once (JMarc) rc
185
186         for (int i = 0 ; i < 8 ; ++i) {
187                 Math_Fonts[i] = LyXFont(LyXFont::ALL_SANE);
188         }
189
190         Math_Fonts[0].setShape(LyXFont::ITALIC_SHAPE);
191
192         Math_Fonts[1].setFamily(LyXFont::SYMBOL_FAMILY);
193
194         Math_Fonts[2].setFamily(LyXFont::SYMBOL_FAMILY);
195         Math_Fonts[2].setShape(LyXFont::ITALIC_SHAPE);
196
197         Math_Fonts[3].setSeries(LyXFont::BOLD_SERIES);
198
199         Math_Fonts[4].setFamily(LyXFont::SANS_FAMILY);
200         Math_Fonts[4].setShape(LyXFont::ITALIC_SHAPE);
201
202         Math_Fonts[5].setFamily(LyXFont::TYPEWRITER_FAMILY);
203
204         Math_Fonts[6].setFamily(LyXFont::ROMAN_FAMILY);
205
206         Math_Fonts[7].setFamily(LyXFont::SANS_FAMILY);
207 }
208
209
210 // returns the nearest enclosing matrix
211 MathArrayInset * matrixpar(int & idx)
212 {
213         idx = 0;
214         return
215                 static_cast<MathArrayInset *> 
216                         (mathcursor ? mathcursor->enclosing(LM_OT_MATRIX, idx) : 0); 
217 }
218
219
220 } // namespace anon
221
222
223 InsetFormulaBase::InsetFormulaBase(MathInset * par)
224         : par_(par)
225 {}
226
227
228 InsetFormulaBase::InsetFormulaBase(InsetFormulaBase const & f)
229         : UpdatableInset(f), par_(static_cast<MathInset *>(f.par_->clone()))
230 {}
231
232
233 InsetFormulaBase::~InsetFormulaBase()
234 {
235 #ifdef WITH_WARNINGS
236 #warning leak this for a while...
237 #endif
238         //delete par_;
239 }
240
241
242 void InsetFormulaBase::read(Buffer const *, LyXLex & lex)
243 {
244         read(lex);
245 }
246
247 void InsetFormulaBase::write(Buffer const *, ostream & os) const
248 {
249         write(os);
250 }
251
252 int InsetFormulaBase::latex(Buffer const *, ostream & os,
253         bool fragile, bool spacing) const
254 {
255         return latex(os, fragile, spacing);
256 }
257
258 int InsetFormulaBase::ascii(Buffer const *, ostream & os, int spacing) const
259 {
260         return ascii(os, spacing);
261 }
262
263 int InsetFormulaBase::linuxdoc(Buffer const *, ostream & os) const
264 {
265         return linuxdoc(os);
266 }
267
268 int InsetFormulaBase::docBook(Buffer const *, ostream & os) const
269 {
270         return docBook(os);
271 }
272
273
274
275 // Check if uses AMS macros
276 void InsetFormulaBase::validate(LaTeXFeatures &) const
277 {}
278
279
280 string const InsetFormulaBase::editMessage() const
281 {
282         return _("Math editor mode");
283 }
284
285
286 void InsetFormulaBase::edit(BufferView * bv, int x, int /*y*/, unsigned int)
287 {
288         mathcursor = new MathCursor(this);
289
290         if (!bv->lockInset(this))
291                 lyxerr[Debug::MATHED] << "Cannot lock inset!!!" << endl;
292
293         par_->Metrics(LM_ST_TEXT);
294         bv->updateInset(this, false);
295         if (x == 0) {
296                 mathcursor->first();
297         } else {
298                 mathcursor->last();
299         }
300         sel_x = 0;
301         sel_y = 0;
302         sel_flag = false;
303 }
304
305
306 void InsetFormulaBase::insetUnlock(BufferView * bv)
307 {
308         if (mathcursor) {
309                 if (mathcursor->InMacroMode()) {
310                         mathcursor->MacroModeClose();
311                         updateLocal(bv);
312                 }
313                 delete mathcursor;
314         }
315         mathcursor = 0;
316         bv->updateInset(this, false);
317 }
318
319
320 void InsetFormulaBase::getCursorPos(BufferView *, int & x, int & y) const
321 {
322         mathcursor->GetPos(x, y);
323         x -= par_->xo();
324         y -= par_->yo();
325 }
326
327
328 void InsetFormulaBase::toggleInsetCursor(BufferView * bv)
329 {
330         if (!mathcursor)
331                 return;
332
333         if (isCursorVisible())
334                 bv->hideLockedInsetCursor();
335         else {
336                 int x;
337                 int y;
338                 mathcursor->GetPos(x, y);
339                 //x -= par_->xo();
340                 y -= par_->yo();
341
342                 LyXFont   font = WhichFont(LM_TC_TEXTRM, LM_ST_TEXT);
343                 int const asc  = lyxfont::maxAscent(font);
344                 int const desc = lyxfont::maxDescent(font);
345
346                 bv->showLockedInsetCursor(x, y, asc, desc);
347         }
348
349         toggleCursorVisible();
350 }
351
352
353 void InsetFormulaBase::showInsetCursor(BufferView * bv, bool)
354 {
355         if (!isCursorVisible()) {
356                 if (mathcursor) {
357                         int x;
358                         int y;
359                         mathcursor->GetPos(x, y);
360                         x -= par_->xo();
361                         y -= par_->yo();
362                         LyXFont font   = WhichFont(LM_TC_TEXTRM, LM_ST_TEXT);
363                         int const asc  = lyxfont::maxAscent(font);
364                         int const desc = lyxfont::maxDescent(font);
365                         bv->fitLockedInsetCursor(x, y, asc, desc);
366                 }
367                 toggleInsetCursor(bv);
368         }
369 }
370
371
372 void InsetFormulaBase::hideInsetCursor(BufferView * bv)
373 {
374         if (isCursorVisible())
375                 toggleInsetCursor(bv);
376 }
377
378
379 void InsetFormulaBase::toggleInsetSelection(BufferView * bv)
380 {
381         if (!mathcursor)
382                 return;
383
384         bv->updateInset(this, false);
385 }
386
387
388 vector<string> const InsetFormulaBase::getLabelList() const
389 {
390   return std::vector<string>();
391 }
392
393
394 void InsetFormulaBase::updateLocal(BufferView * bv)
395 {
396         par_->Metrics(LM_ST_TEXT);
397         bv->updateInset(this, true);
398 }
399
400
401 void InsetFormulaBase::insetButtonRelease(BufferView * bv,
402                                           int x, int y, int /*button*/)
403 {
404         if (mathcursor) {
405                 hideInsetCursor(bv);
406                 x += par_->xo();
407                 y += par_->yo();
408                 mathcursor->SetPos(x, y);
409                 showInsetCursor(bv);
410                 if (sel_flag) {
411                         sel_flag = false;
412                         sel_x = 0;
413                         sel_y = 0;
414                 }
415                 bv->updateInset(this, false);
416         }
417 }
418
419
420 void InsetFormulaBase::insetButtonPress(BufferView * bv,
421                                         int x, int y, int /*button*/)
422 {
423         sel_flag = false;
424         sel_x = x;
425         sel_y = y;
426         if (mathcursor && mathcursor->Selection()) {
427                 mathcursor->SelClear();
428                 bv->updateInset(this, false);
429         }
430 }
431
432
433 void InsetFormulaBase::insetMotionNotify(BufferView * bv,
434                                          int x, int y, int /*button*/)
435 {
436         if (sel_x && sel_y && abs(x-sel_x) > 4 && !sel_flag) {
437                 sel_flag = true;
438                 hideInsetCursor(bv);
439                 mathcursor->SetPos(sel_x + par_->xo(), sel_y + par_->yo());
440                 mathcursor->SelStart();
441                 showInsetCursor(bv);
442                 mathcursor->GetPos(sel_x, sel_y);
443         } else if (sel_flag) {
444                 hideInsetCursor(bv);
445                 x += par_->xo();
446                 y += par_->yo();
447                 mathcursor->SetPos(x, y);
448                 showInsetCursor(bv);
449                 mathcursor->GetPos(x, y);
450                 if (sel_x != x || sel_y != y)
451                         bv->updateInset(this, false);
452                 sel_x = x;
453                 sel_y = y;
454         }
455 }
456
457
458 void InsetFormulaBase::insetKeyPress(XKeyEvent *)
459 {
460         lyxerr[Debug::MATHED]
461                 << "Used InsetFormulaBase::InsetKeyPress." << endl;
462 }
463
464
465
466 UpdatableInset::RESULT
467 InsetFormulaBase::localDispatch(BufferView * bv, kb_action action,
468                             string const & arg)
469 {
470         //lyxerr << "InsetFormulaBase::LocalDispatch: act: " << action
471         //      << " arg: '" << arg << "' cursor: " << mathcursor << "\n";
472         //   extern char *dispatch_result;
473
474         if (!mathcursor) 
475                 return UNDISPATCHED;
476
477         MathTextCodes varcode = LM_TC_MIN;
478         bool was_macro = mathcursor->InMacroMode();
479         bool sel = false;
480         bool was_selection = mathcursor->Selection();
481         RESULT result = DISPATCHED;
482
483         hideInsetCursor(bv);
484
485         if (mathcursor->getLastCode() == LM_TC_TEX)
486                 varcode = LM_TC_TEX;
487
488         mathcursor->normalize();
489
490         switch (action) {
491
492                 // --- Cursor Movements ---------------------------------------------
493
494         case LFUN_RIGHTSEL:
495                 sel = true; // fall through...
496
497         case LFUN_RIGHT:
498                 result = DISPATCH_RESULT(mathcursor->Right(sel));
499                 updateLocal(bv);
500                 break;
501
502
503         case LFUN_LEFTSEL:
504                 sel = true; // fall through
505
506         case LFUN_LEFT:
507                 result = DISPATCH_RESULT(mathcursor->Left(sel));
508                 updateLocal(bv);
509                 break;
510
511
512         case LFUN_UPSEL:
513                 sel = true;
514
515         case LFUN_UP:
516                 result = DISPATCH_RESULT(mathcursor->Up(sel));
517                 updateLocal(bv);
518                 break;
519
520
521         case LFUN_DOWNSEL:
522                 sel = true;
523
524         case LFUN_DOWN:
525                 result = DISPATCH_RESULT(mathcursor->Down(sel));
526                 updateLocal(bv);
527                 break;
528
529         case LFUN_HOME:
530                 mathcursor->Home();
531                 updateLocal(bv);
532                 break;
533
534         case LFUN_END:
535                 mathcursor->End();
536                 updateLocal(bv);
537                 break;
538
539         case LFUN_DELETE_LINE_FORWARD:
540                 bv->lockedInsetStoreUndo(Undo::DELETE);
541                 mathcursor->DelLine();
542                 updateLocal(bv);
543                 break;
544
545         case LFUN_TAB:
546                 mathcursor->idxNext();
547                 updateLocal(bv);
548                 break;
549
550         case LFUN_SHIFT_TAB:
551                 mathcursor->idxPrev();
552                 updateLocal(bv);
553                 break;
554
555         case LFUN_TABINSERT:
556                 bv->lockedInsetStoreUndo(Undo::EDIT);
557                 mathcursor->splitCell();
558                 updateLocal(bv);
559                 break;
560
561         case LFUN_BACKSPACE:
562                 if (!mathcursor->InMacroMode() && mathcursor->pos() == 0) {
563                         bv->lockedInsetStoreUndo(Undo::DELETE);
564                         mathcursor->pullArg();
565                         bv->updateInset(this, true);
566                         break;
567                 }
568                 if (!mathcursor->Left())
569                         break;
570                 // fall through...
571
572         case LFUN_DELETE:
573                 bv->lockedInsetStoreUndo(Undo::DELETE);
574                 mathcursor->Delete();
575                 bv->updateInset(this, true);
576                 break;
577
578                 //    case LFUN_GETXY:
579                 //      sprintf(dispatch_buffer, "%d %d",);
580                 //      dispatch_result = dispatch_buffer;
581                 //      break;
582         case LFUN_SETXY:
583         {
584                 lyxerr << "LFUN_SETXY broken!\n";
585                 int x;
586                 int y;
587                 int x1;
588                 int y1;
589                 istringstream is(arg.c_str());
590                 is >> x >> y;
591                 par_->GetXY(x1, y1);
592                 mathcursor->SetPos(x1 + x, y1 + y);
593                 updateLocal(bv);
594         }
595         break;
596
597                 // cursor selection ---------------------------- 
598
599         case LFUN_PASTE:
600                 if (was_macro)
601                         mathcursor->MacroModeClose();
602                 bv->lockedInsetStoreUndo(Undo::INSERT);
603                 mathcursor->SelPaste();
604                 updateLocal(bv);
605                 break;
606
607         case LFUN_CUT:
608                 bv->lockedInsetStoreUndo(Undo::DELETE);
609                 mathcursor->SelCut();
610                 updateLocal(bv);
611                 break;
612
613         case LFUN_COPY:
614                 mathcursor->SelCopy();
615                 break;
616
617         case LFUN_HOMESEL:
618         case LFUN_ENDSEL:
619         case LFUN_WORDRIGHTSEL:
620         case LFUN_WORDLEFTSEL:
621                 break;
622
623                 // --- accented characters ------------------------------
624
625         case LFUN_UMLAUT:     mathcursor->setAccent(LM_ddot); break;
626         case LFUN_CIRCUMFLEX: mathcursor->setAccent(LM_hat); break;
627         case LFUN_GRAVE:      mathcursor->setAccent(LM_grave); break;
628         case LFUN_ACUTE:      mathcursor->setAccent(LM_acute); break;
629         case LFUN_TILDE:      mathcursor->setAccent(LM_tilde); break;
630         case LFUN_MACRON:     mathcursor->setAccent(LM_bar); break;
631         case LFUN_DOT:        mathcursor->setAccent(LM_dot); break;
632         case LFUN_CARON:      mathcursor->setAccent(LM_check); break;
633         case LFUN_BREVE:      mathcursor->setAccent(LM_breve); break;
634         case LFUN_VECTOR:     mathcursor->setAccent(LM_vec); break;
635
636                 // Greek mode
637         case LFUN_GREEK:
638                 if (!greek_kb_flag) {
639                         greek_kb_flag = 1;
640                         bv->owner()->message(_("Math greek mode on"));
641                 } else
642                         greek_kb_flag = 0;
643                 break;
644
645                 // Greek keyboard
646         case LFUN_GREEK_TOGGLE:
647                 greek_kb_flag = greek_kb_flag ? 0 : 2;
648                 if (greek_kb_flag)
649                         bv->owner()->message(_("Math greek keyboard on"));
650                 else
651                         bv->owner()->message(_("Math greek keyboard off"));
652                 break;
653
654                 //  Math fonts
655         case LFUN_BOLD:    handleFont(bv, LM_TC_BF); break;
656         case LFUN_SANS:    handleFont(bv, LM_TC_SF); break;
657         case LFUN_EMPH:    handleFont(bv, LM_TC_CAL); break;
658         case LFUN_ROMAN:   handleFont(bv, LM_TC_RM); break;
659         case LFUN_CODE:    handleFont(bv, LM_TC_TT); break;
660         case LFUN_DEFAULT: handleFont(bv, LM_TC_VAR); break;
661
662         case LFUN_MATH_MODE:
663                 handleFont(bv, LM_TC_TEXTRM);
664                 //bv->owner()->message(_("math text mode toggled"));
665                 break;
666
667 #ifndef NO_LATEX
668         case LFUN_TEX:
669                 if (!mathcursor->Selection()) {
670                         mathcursor->handleFont(LM_TC_TEX);
671                         //bv->owner()->message(_("TeX mode toggled"));
672                 }
673                 break;
674 #endif
675
676         case LFUN_MATH_LIMITS:
677                 bv->lockedInsetStoreUndo(Undo::INSERT);
678                 if (mathcursor->toggleLimits())
679                         updateLocal(bv);
680                 break;
681
682         case LFUN_MATH_SIZE:
683                 if (!arg.empty()) {
684                         bv->lockedInsetStoreUndo(Undo::INSERT);
685                         latexkeys const * l = in_word_set(arg);
686                         mathcursor->SetSize(MathStyles(l ? l->id : static_cast<unsigned int>(-1)));
687                         updateLocal(bv);
688                 }
689                 break;
690
691         case LFUN_INSERT_MATRIX:
692                 if (!arg.empty()) {
693                         bv->lockedInsetStoreUndo(Undo::INSERT);
694                         mathcursor->Interpret("matrix " + arg);
695                         updateLocal(bv);
696                 }
697                 break;
698
699         case LFUN_INSERT_MATH:
700                 if (!arg.empty()) {
701                         bv->lockedInsetStoreUndo(Undo::INSERT);
702                         mathcursor->Interpret(arg);
703                         updateLocal(bv);
704                 }
705                 break;
706
707         case LFUN_MATH_DELIM:
708         {
709                 bv->lockedInsetStoreUndo(Undo::INSERT);
710                 int ilt = '(';
711                 int irt = '.';
712                 static const string vdelim("(){}[]./|");
713                 lyxerr << "formulabase::LFUN_MATH_DELIM, arg: '" << arg << "'\n";
714
715                 if (arg.empty())
716                         break;
717
718                 istringstream is(arg.c_str());
719                 string lt;
720                 string rt;
721                 is >> lt >> rt;
722                 lyxerr << "formulabase::LFUN_MATH_DELIM, lt: '" << lt << "'\n";
723                 lyxerr << "formulabase::LFUN_MATH_DELIM, rt: '" << rt << "'\n";
724
725                 if (lt.size() > 1) {
726                         latexkeys const * l = in_word_set(lt);
727                         if (l)
728                                 ilt = l->id;
729                 } else if (vdelim.find(lt[0]) != string::npos)
730                                 ilt = lt[0];
731
732                 if (rt.size() > 1) {
733                         latexkeys const * l = in_word_set(rt);
734                         if (l)
735                                 irt = l->id;
736                 } else if (vdelim.find(rt[0]) != string::npos)
737                                 irt = rt[0];
738
739                 if (mathcursor->selection) {
740                         MathDelimInset * p = new MathDelimInset(ilt, irt);
741                         MathArray ar;
742                         mathcursor->selArray(ar);
743                         lyxerr << "selarray: " << ar << "\n";
744                         p->cell(0) = ar; 
745                         mathcursor->insert(p);
746                 } else {
747                         mathcursor->insert(new MathDelimInset(ilt, irt));
748                 }
749                 updateLocal(bv);
750                 break;
751         }
752
753         case LFUN_PROTECTEDSPACE:
754                 bv->lockedInsetStoreUndo(Undo::INSERT);
755                 mathcursor->insert(new MathSpaceInset(1));
756                 updateLocal(bv);
757                 break;
758
759         case LFUN_UNDO:
760                 bv->owner()->message(_("Invalid action in math mode!"));
761                 break;
762
763
764         case LFUN_MATH_HALIGN:
765         {
766                 bv->lockedInsetStoreUndo(Undo::INSERT);
767                 lyxerr << "handling halign '" << arg << "'\n";
768                 int idx;
769                 MathArrayInset * p = matrixpar(idx);
770                 if (!p)
771                         break; 
772                 p->halign(arg.size() ? arg[0] : 'c', p->col(idx));
773                 updateLocal(bv);
774                 break;
775         }
776
777         case LFUN_MATH_VALIGN:
778         {
779                 bv->lockedInsetStoreUndo(Undo::INSERT);
780                 lyxerr << "handling valign '" << arg << "'\n";
781                 int idx;
782                 MathArrayInset * p = matrixpar(idx);
783                 if (!p)
784                         break; 
785                 p->valign(arg.size() ? arg[0] : 'c');
786                 updateLocal(bv);
787                 break;
788         }
789
790         case LFUN_MATH_ROW_INSERT:
791         {
792                 bv->lockedInsetStoreUndo(Undo::INSERT);
793                 int idx;
794                 MathArrayInset * p = matrixpar(idx);
795                 lyxerr << " calling LFUN_MATH_ROW_INSERT on " << p << endl;
796                 if (!p)
797                         break; 
798                 p->addRow(p->row(idx));
799                 updateLocal(bv);
800                 break;
801         }
802
803         case LFUN_MATH_ROW_DELETE:
804         {
805                 bv->lockedInsetStoreUndo(Undo::INSERT);
806                 int idx;
807                 MathArrayInset * p = matrixpar(idx);
808                 lyxerr << " calling LFUN_MATH_ROW_DELETE on " << p << endl;
809                 if (!p)
810                         break; 
811                 p->delRow(p->row(idx));
812                 updateLocal(bv);
813                 break;
814         }
815
816         case LFUN_MATH_COLUMN_INSERT:
817         {
818                 bv->lockedInsetStoreUndo(Undo::INSERT);
819                 int idx;
820                 MathArrayInset * p = matrixpar(idx);
821                 if (!p)
822                         break; 
823                 p->addCol(p->col(idx));
824                 updateLocal(bv);
825                 break;
826         }
827
828         case LFUN_MATH_COLUMN_DELETE:
829         {
830                 bv->lockedInsetStoreUndo(Undo::INSERT);
831                 int idx;
832                 MathArrayInset * p = matrixpar(idx);
833                 if (!p)
834                         break; 
835                 p->delCol(p->col(idx));
836                 updateLocal(bv);
837                 break;
838         }
839
840         case LFUN_EXEC_COMMAND:
841                 result = UNDISPATCHED;
842                 break;
843
844         default:
845                 if ((action == -1 || action == LFUN_SELFINSERT) && !arg.empty()) {
846                         unsigned char c = arg[0];
847                         lyxerr << "char: '" << c << "'  int: " << int(c) << endl;
848                         //owner_->getIntl()->getTrans().TranslateAndInsert(c, lt);      
849                         lyxerr << "trans: '" << c << "'  int: " << int(c) << endl;
850                         bv->lockedInsetStoreUndo(Undo::INSERT);
851
852                         if (c == ' ' && mathcursor->getAccent() == LM_hat) {
853                                 c = '^';
854                                 mathcursor->setAccent(0);
855                         }
856
857                         if (c == 0) {      // Dead key, do nothing
858                                 //lyxerr << "deadkey" << endl;
859                                 break;
860                         }
861
862                         if (isalpha(c)) {
863                                 if (mathcursor->getLastCode() == LM_TC_TEX) {
864                                         mathcursor->MacroModeOpen();
865                                         mathcursor->clearLastCode();
866                                         varcode = LM_TC_MIN;
867                                 } else if (!varcode) {          
868                                         short f = mathcursor->getLastCode() ?
869                                                 mathcursor->getLastCode() :
870                                                 mathcursor->nextCode();
871                                         varcode = MathIsAlphaFont(f) ?
872                                                 static_cast<MathTextCodes>(f) :
873                                                 LM_TC_VAR;
874                                 }
875                                 
876                                 //           lyxerr << "Varcode << vardoce;
877                                 MathTextCodes char_code = varcode;
878                                 if (greek_kb_flag) {
879                                         char greek[26] =
880                                         {'A', 'B', 'X',  0 , 'E',  0 ,  0 , 'H', 'I',  0 ,
881                                          'K',  0 , 'M', 'N', 'O',  0 ,  0 , 'P',  0 , 'T',
882                                          'Y',  0,   0,   0,   0 , 'Z' };
883                                         
884                                         if ('A' <= c && c <= 'Z' && greek[c - 'A']) {
885                                                 char_code = LM_TC_RM;
886                                                 c = greek[c - 'A'];
887                                         } else
888                                                 char_code = LM_TC_SYMB;
889                                 }
890                                 
891                                 mathcursor->insert(c, char_code);
892                                 
893                                 if (greek_kb_flag && char_code == LM_TC_RM )
894                                         mathcursor->setLastCode(LM_TC_VAR);
895                                 
896                                 varcode = LM_TC_MIN;
897                                 
898                                 if (greek_kb_flag < 2)
899                                         greek_kb_flag = 0;
900                                 
901                         } else if (strchr("!,:;{}", c) && (varcode == LM_TC_TEX||was_macro)) {
902                                 mathcursor->insert(c, LM_TC_TEX);
903                                 if (c == '{') {
904                                         mathcursor->insert('}', LM_TC_TEX);
905                                         mathcursor->Left();
906                                 }
907                                 mathcursor->clearLastCode();
908                                 //             varcode = LM_TC_MIN;
909                         } else if (c == '_' && varcode == LM_TC_TEX) {
910                                 mathcursor->insert(c, LM_TC_SPECIAL);
911                                 mathcursor->clearLastCode();
912                                 //             varcode = LM_TC_MIN;
913                         } else if ('0' <= c && c <= '9' && (varcode == LM_TC_TEX||was_macro)) {
914                                 mathcursor->MacroModeOpen();
915                                 mathcursor->clearLastCode();
916                                 mathcursor->insert(c, LM_TC_MIN);
917                         } else if (('0' <= c && c <= '9') || strchr(";:!|[]().,?", c)) {
918                                 MathTextCodes code = mathcursor->getLastCode();
919                                 if (code != LM_TC_TEXTRM)
920                                         code = LM_TC_CONST;
921                                 mathcursor->insert(c, code);
922                         } else if (strchr("+/-*<>=", c)) {
923                                 MathTextCodes code = mathcursor->getLastCode();
924                                 if (code != LM_TC_TEXTRM)
925                                         code = LM_TC_BOP;
926                                 mathcursor->insert(c, code);
927                         } else if (strchr(latex_special_chars, c) && c != '_') {
928                                 MathTextCodes code = mathcursor->getLastCode();
929                                 if (code != LM_TC_TEXTRM)
930                                         code = LM_TC_SPECIAL;
931                                 mathcursor->insert(c, code);
932                         } else if (c == '_' || c == '^') {
933                                 char s[2];
934                                 s[0] = c;
935                                 s[1] = 0;
936                                 mathcursor->Interpret(s);
937                         } else if (c == ' ') {  
938                                 if (!varcode) { 
939                                         short f = (mathcursor->getLastCode()) ?
940                                                 mathcursor->getLastCode() :
941                                                 mathcursor->nextCode();
942                                         varcode = MathIsAlphaFont(f) ?
943                                                 static_cast<MathTextCodes>(f) :
944                                                 LM_TC_VAR;
945                                 }
946                                 
947                                 if (varcode == LM_TC_TEXTRM) {
948                                         mathcursor->insert(c, LM_TC_TEXTRM);
949                                 } else if (was_macro) {
950                                         mathcursor->MacroModeClose();
951                                 } else {
952                                         if (!mathcursor->pop())
953                                                 result = FINISHED;
954                                         mathcursor->plainRight();
955                                 }
956                         } else if (c == '\'' || c == '@') {
957                                 mathcursor->insert (c, LM_TC_VAR);
958                         } else if (c == '\\') {
959                                 if (was_macro)
960                                         mathcursor->MacroModeClose();
961                                 bv->owner()->message(_("TeX mode"));
962                                 mathcursor->setLastCode(LM_TC_TEX);
963                         }
964                         updateLocal(bv);
965                 } else if (action == LFUN_MATH_PANEL) {
966                         result = UNDISPATCHED;
967                 } else {
968                         lyxerr << "Closed by action " << action << endl;
969                         result =  FINISHED;
970                 }
971         }
972
973         if (mathcursor)
974                 mathcursor->normalize();
975
976         if (mathcursor && was_macro != mathcursor->InMacroMode()
977                                 && action >= 0
978                                 && action != LFUN_BACKSPACE) 
979                 updateLocal(bv);
980         
981         //if (mathcursor)
982         //              updateLocal(bv);
983
984         if (mathcursor && (mathcursor->Selection() || was_selection))
985                 toggleInsetSelection(bv);
986
987         if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
988             result == UNDISPATCHED)
989                 showInsetCursor(bv);
990         else
991                 bv->unlockInset(this);
992
993         return result;  // original version
994 }
995
996
997
998 /* FIXME: math-greek-toggle seems to work OK, but math-greek doesn't turn
999  * on greek mode */
1000 bool math_insert_greek(BufferView * bv, char c)
1001 {
1002         if (!bv->available())
1003                 return false;
1004
1005         if (!isalpha(c))
1006                 return false;
1007
1008         string tmp;
1009         tmp = c;
1010         if (!bv->theLockingInset() || bv->theLockingInset()->isTextInset()) {
1011                 int greek_kb_flag_save = greek_kb_flag;
1012                 InsetFormula * new_inset = new InsetFormula();
1013                 bv->beforeChange(bv->text);
1014                 if (!bv->insertInset(new_inset)) {
1015                         delete new_inset;
1016                         return false;
1017                 }
1018                 //Update(1);//BUG
1019                 new_inset->edit(bv, 0, 0, 0);
1020                 new_inset->localDispatch(bv, LFUN_SELFINSERT, tmp);
1021                 if (greek_kb_flag_save < 2) {
1022                         bv->unlockInset(new_inset); // bv->theLockingInset());
1023                         bv->text->cursorRight(bv, true);
1024                 }
1025         } else
1026                 if (bv->theLockingInset()->lyxCode() == Inset::MATH_CODE ||
1027                                 bv->theLockingInset()->lyxCode() == Inset::MATHMACRO_CODE)
1028                         static_cast<InsetFormula*>(bv->theLockingInset())->localDispatch(bv, LFUN_SELFINSERT, tmp);
1029                 else
1030                         lyxerr << "Math error: attempt to write on a wrong "
1031                                 "class of inset." << endl;
1032         return true;
1033 }
1034
1035
1036
1037 Inset::Code InsetFormulaBase::lyxCode() const
1038 {
1039         return Inset::MATH_CODE;
1040 }
1041
1042
1043 LyXFont const InsetFormulaBase::convertFont(LyXFont const & f) const
1044 {
1045         // We have already discussed what was here
1046         LyXFont font(f);
1047 #ifndef NO_LATEX
1048         font.setLatex(LyXFont::OFF);
1049 #endif
1050         return font;
1051 }
1052
1053 MathInset * InsetFormulaBase::par() const
1054 {
1055         return par_;
1056 }
1057
1058
1059 void mathDispatchCreation(BufferView * bv, string const & arg, bool display)
1060 {
1061         if (bv->available()) {
1062 // Feature "Read math inset from selection" disabled.
1063 //              // use selection if available..
1064 //              string sel;
1065 //              if (action == LFUN_MATH_IMPORT_SELECTION)
1066 //                      sel = "";
1067 //              else
1068 //                      sel = bv->getLyXText()->selectionAsString(bv->buffer());
1069
1070                         InsetFormula * f;
1071 //              if (sel.empty()) {
1072                                 f = new InsetFormula;
1073                                 openNewInset(bv, f);
1074                                 // don't do that also for LFUN_MATH_MODE unless you want end up with
1075                                 // always changing to mathrm when opening an inlined inset
1076                                 // -- I really hate "LyXfunc overloading"...
1077                                 if (display)
1078                                         f->localDispatch(bv, LFUN_MATH_DISPLAY, string());
1079                                 f->localDispatch(bv, LFUN_INSERT_MATH, arg);
1080 //              } else {
1081 //                      f = new InsetFormula(sel);
1082 //                      bv->getLyXText()->cutSelection(bv);
1083 //                      openNewInset(bv, f);
1084 //              }
1085         }
1086         bv->owner()->getLyXFunc()->setMessage(N_("Math editor mode"));
1087 }
1088
1089 void mathDispatchMathDisplay(BufferView * bv, string const & arg)
1090 {
1091         mathDispatchCreation(bv, arg, true);
1092 }
1093         
1094 void mathDispatchMathMode(BufferView * bv, string const & arg)
1095 {
1096         mathDispatchCreation(bv, arg, false);
1097 }
1098
1099 void mathDispatchMathImportSelection(BufferView * bv, string const & arg)
1100 {
1101         mathDispatchCreation(bv, arg, true);
1102 }
1103
1104 void mathDispatchMathMacro(BufferView * bv, string const & arg)
1105 {
1106         if (bv->available()) {
1107                 string s(arg);
1108                 if (s.empty())
1109                         bv->owner()->getLyXFunc()->setErrorMessage(N_("Missing argument"));
1110                 else {
1111                         string const s1 = token(s, ' ', 1);
1112                         int const na = s1.empty() ? 0 : lyx::atoi(s1);
1113                         openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
1114                 }
1115         }
1116 }
1117
1118 void mathDispatchMathDelim(BufferView * bv, string const & arg)
1119 {          
1120         if (bv->available()) { 
1121                 if (openNewInset(bv, new InsetFormula))
1122                         bv->theLockingInset()->localDispatch(bv, LFUN_MATH_DELIM, arg);
1123         }
1124 }          
1125
1126
1127 void mathDispatchInsertMatrix(BufferView * bv, string const & arg)
1128 {          
1129         if (bv->available()) { 
1130                 if (openNewInset(bv, new InsetFormula))
1131                         bv->theLockingInset()->localDispatch(bv, LFUN_INSERT_MATRIX, arg);
1132         }
1133 }          
1134
1135 void mathDispatchInsertMath(BufferView * bv, string const & arg)
1136 {
1137         if (bv->available()) {
1138                 if (arg.size() && arg[0] == '\\') {
1139                         InsetFormula * f = new InsetFormula(arg);
1140                         openNewInset(bv, f);
1141                 } else {
1142                         mathDispatchMathMode(bv, arg);
1143                 }
1144         }
1145 }
1146