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