]> git.lyx.org Git - lyx.git/blob - src/mathed/formulabase.C
baed9845a60ac467f28a3c50411109ab55515ed9
[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                 // cursor selection ---------------------------- 
511
512         case LFUN_PASTE:
513                 if (was_macro)
514                         mathcursor->MacroModeClose();
515                 bv->lockedInsetStoreUndo(Undo::INSERT);
516                 mathcursor->SelPaste();
517                 updateLocal(bv, true);
518                 break;
519
520         case LFUN_CUT:
521                 bv->lockedInsetStoreUndo(Undo::DELETE);
522                 mathcursor->SelCut();
523                 updateLocal(bv, true);
524                 break;
525
526         case LFUN_COPY:
527                 mathcursor->SelCopy();
528                 break;
529
530         case LFUN_HOMESEL:
531         case LFUN_ENDSEL:
532         case LFUN_WORDRIGHTSEL:
533         case LFUN_WORDLEFTSEL:
534                 break;
535
536                 // --- accented characters ------------------------------
537
538         case LFUN_UMLAUT:     handleAccent(bv, "ddot", LM_ddot); break;
539         case LFUN_CIRCUMFLEX: handleAccent(bv, "hat", LM_hat); break;
540         case LFUN_GRAVE:      handleAccent(bv, "grave", LM_grave); break;
541         case LFUN_ACUTE:      handleAccent(bv, "acute", LM_acute); break;
542         case LFUN_TILDE:      handleAccent(bv, "tilde", LM_tilde); break;
543         case LFUN_MACRON:     handleAccent(bv, "bar", LM_bar); break;
544         case LFUN_DOT:        handleAccent(bv, "dot", LM_dot); break;
545         case LFUN_CARON:      handleAccent(bv, "check", LM_check); break;
546         case LFUN_BREVE:      handleAccent(bv, "breve", LM_breve); break;
547         case LFUN_VECTOR:     handleAccent(bv, "vec", LM_vec); break;
548
549                 // Greek mode
550         case LFUN_GREEK:
551                 if (!greek_kb_flag) {
552                         greek_kb_flag = 1;
553                         bv->owner()->message(_("Math greek mode on"));
554                 } else
555                         greek_kb_flag = 0;
556                 break;
557
558                 // Greek keyboard
559         case LFUN_GREEK_TOGGLE:
560                 greek_kb_flag = greek_kb_flag ? 0 : 2;
561                 if (greek_kb_flag)
562                         bv->owner()->message(_("Math greek keyboard on"));
563                 else
564                         bv->owner()->message(_("Math greek keyboard off"));
565                 break;
566
567                 //  Math fonts
568         case LFUN_BOLD:    handleFont(bv, LM_TC_BF); break;
569         case LFUN_SANS:    handleFont(bv, LM_TC_SF); break;
570         case LFUN_EMPH:    handleFont(bv, LM_TC_CAL); break;
571         case LFUN_ROMAN:   handleFont(bv, LM_TC_RM); break;
572         case LFUN_CODE:    handleFont(bv, LM_TC_TT); break;
573         case LFUN_DEFAULT: handleFont(bv, LM_TC_VAR); break;
574
575         case LFUN_MATH_MODE:
576                 handleFont(bv, LM_TC_TEXTRM);
577                 //bv->owner()->message(_("math text mode toggled"));
578                 break;
579
580 #ifndef NO_LATEX
581         case LFUN_TEX:
582                 if (!mathcursor->Selection()) {
583                         mathcursor->handleFont(LM_TC_TEX);
584                         //bv->owner()->message(_("TeX mode toggled"));
585                 }
586                 break;
587 #endif
588
589         case LFUN_MATH_LIMITS:
590                 bv->lockedInsetStoreUndo(Undo::INSERT);
591                 if (mathcursor->toggleLimits())
592                         updateLocal(bv, true);
593                 break;
594
595         case LFUN_MATH_SIZE:
596                 if (!arg.empty()) {
597                         bv->lockedInsetStoreUndo(Undo::INSERT);
598                         latexkeys const * l = in_word_set(arg);
599                         mathcursor->SetSize(MathStyles(l ? l->id : static_cast<unsigned int>(-1)));
600                         updateLocal(bv, true);
601                 }
602                 break;
603
604         case LFUN_INSERT_MATRIX:
605                 if (!arg.empty()) {
606                         bv->lockedInsetStoreUndo(Undo::INSERT);
607                         mathcursor->Interpret("matrix " + arg);
608                         updateLocal(bv, true);
609                 }
610                 break;
611
612         case LFUN_INSERT_MATH:
613                 if (!arg.empty()) {
614                         bv->lockedInsetStoreUndo(Undo::INSERT);
615                         mathcursor->Interpret(arg);
616                         updateLocal(bv, true);
617                 }
618                 break;
619
620         case LFUN_MATH_DELIM:
621         {
622                 bv->lockedInsetStoreUndo(Undo::INSERT);
623                 static const string vdelim("(){}[]./|");
624                 //lyxerr << "formulabase::LFUN_MATH_DELIM, arg: '" << arg << "'\n";
625
626                 if (arg.empty())
627                         break;
628
629                 // try to read integers first
630                 int ilt = '(';
631                 int irt = '.';
632                 istringstream is(arg.c_str());
633                 is >> ilt >> irt;
634
635                 if (!is) { // ok, the beasties are no integers... try something else
636                         ilt = '(';
637                         irt = '.';
638
639                         istringstream is(arg.c_str());
640                         string lt;
641                         string rt;
642                         is >> lt >> rt;
643                         //lyxerr << "formulabase::LFUN_MATH_DELIM, lt: '" << lt << "'\n";
644                         //lyxerr << "formulabase::LFUN_MATH_DELIM, rt: '" << rt << "'\n";
645
646                         if (lt.size() > 1) {
647                                 latexkeys const * l = in_word_set(lt);
648                                 if (l)
649                                         ilt = l->id;
650                         } else if (vdelim.find(lt[0]) != string::npos)
651                                         ilt = lt[0];
652
653                         if (rt.size() > 1) {
654                                 latexkeys const * l = in_word_set(rt);
655                                 if (l)
656                                         irt = l->id;
657                         } else if (vdelim.find(rt[0]) != string::npos)
658                                         irt = rt[0];
659                 }
660
661                 handleDelim(bv, ilt, irt);
662                 updateLocal(bv, true);
663                 break;
664         }
665
666         case LFUN_PROTECTEDSPACE:
667                 //lyxerr << " called LFUN_PROTECTEDSPACE\n";
668                 bv->lockedInsetStoreUndo(Undo::INSERT);
669                 mathcursor->insert(new MathSpaceInset(1));
670                 updateLocal(bv, true);
671                 break;
672
673         case LFUN_UNDO:
674                 bv->owner()->message(_("Invalid action in math mode!"));
675                 break;
676
677
678         case LFUN_MATH_HALIGN:
679         {
680                 bv->lockedInsetStoreUndo(Undo::INSERT);
681                 lyxerr << "handling halign '" << arg << "'\n";
682                 int idx;
683                 MathArrayInset * p = matrixpar(idx);
684                 if (!p)
685                         break; 
686                 p->halign(arg.size() ? arg[0] : 'c', p->col(idx));
687                 updateLocal(bv, true);
688                 break;
689         }
690
691         case LFUN_MATH_VALIGN:
692         {
693                 bv->lockedInsetStoreUndo(Undo::INSERT);
694                 lyxerr << "handling valign '" << arg << "'\n";
695                 int idx;
696                 MathArrayInset * p = matrixpar(idx);
697                 if (!p)
698                         break; 
699                 p->valign(arg.size() ? arg[0] : 'c');
700                 updateLocal(bv, true);
701                 break;
702         }
703
704         case LFUN_MATH_ROW_INSERT:
705         {
706                 bv->lockedInsetStoreUndo(Undo::INSERT);
707                 int idx;
708                 MathArrayInset * p = matrixpar(idx);
709                 lyxerr << " calling LFUN_MATH_ROW_INSERT on " << p << endl;
710                 if (!p)
711                         break; 
712                 p->addRow(p->row(idx));
713                 updateLocal(bv, true);
714                 break;
715         }
716
717         case LFUN_MATH_ROW_DELETE:
718         {
719                 bv->lockedInsetStoreUndo(Undo::INSERT);
720                 int idx;
721                 MathArrayInset * p = matrixpar(idx);
722                 lyxerr << " calling LFUN_MATH_ROW_DELETE on " << p << endl;
723                 if (!p)
724                         break; 
725                 p->delRow(p->row(idx));
726                 updateLocal(bv, true);
727                 break;
728         }
729
730         case LFUN_MATH_COLUMN_INSERT:
731         {
732                 bv->lockedInsetStoreUndo(Undo::INSERT);
733                 int idx;
734                 MathArrayInset * p = matrixpar(idx);
735                 if (!p)
736                         break; 
737                 p->addCol(p->col(idx));
738                 updateLocal(bv, true);
739                 break;
740         }
741
742         case LFUN_MATH_COLUMN_DELETE:
743         {
744                 bv->lockedInsetStoreUndo(Undo::INSERT);
745                 int idx;
746                 MathArrayInset * p = matrixpar(idx);
747                 if (!p)
748                         break; 
749                 p->delCol(p->col(idx));
750                 updateLocal(bv, true);
751                 break;
752         }
753
754         case LFUN_EXEC_COMMAND:
755                 result = UNDISPATCHED;
756                 break;
757
758         default:
759                 if ((action == -1 || action == LFUN_SELFINSERT) && !arg.empty()) {
760                         unsigned char c = arg[0];
761
762                         lyxerr << "Action: " << action << endl;
763                         
764                         lyxerr << "char: '" << c << "'  int: " << int(c) << endl;
765                         //owner_->getIntl()->getTrans().TranslateAndInsert(c, lt);      
766                         //lyxerr << "trans: '" << c << "'  int: " << int(c) << endl;
767                         bv->lockedInsetStoreUndo(Undo::INSERT);
768
769                         if (c == 0) {      // Dead key, do nothing
770                                 //lyxerr << "deadkey" << endl;
771                                 break;
772                         }
773
774                         if (isalpha(c)) {
775                                 if (mathcursor->getLastCode() == LM_TC_TEX) {
776                                         mathcursor->MacroModeOpen();
777                                         mathcursor->clearLastCode();
778                                         varcode = LM_TC_MIN;
779                                 } else if (!varcode) {          
780                                         MathTextCodes f = mathcursor->getLastCode() ?
781                                                 mathcursor->getLastCode() :
782                                                 mathcursor->nextCode();
783                                         varcode = MathIsAlphaFont(f) ?
784                                                 static_cast<MathTextCodes>(f) :
785                                                 LM_TC_VAR;
786                                 }
787                                 
788                                 //           lyxerr << "Varcode << vardoce;
789                                 MathTextCodes char_code = varcode;
790                                 if (greek_kb_flag) {
791                                         char greek[26] =
792                                         {'A', 'B', 'X',  0 , 'E',  0 ,  0 , 'H', 'I',  0 ,
793                                          'K',  0 , 'M', 'N', 'O',  0 ,  0 , 'P',  0 , 'T',
794                                          'Y',  0,   0,   0,   0 , 'Z' };
795                                         
796                                         if ('A' <= c && c <= 'Z' && greek[c - 'A']) {
797                                                 char_code = LM_TC_RM;
798                                                 c = greek[c - 'A'];
799                                         } else
800                                                 char_code = LM_TC_SYMB;
801                                 }
802                                 
803                                 mathcursor->insert(c, char_code);
804                                 
805                                 if (greek_kb_flag && char_code == LM_TC_RM )
806                                         mathcursor->setLastCode(LM_TC_VAR);
807                                 
808                                 varcode = LM_TC_MIN;
809                                 
810                                 if (greek_kb_flag < 2)
811                                         greek_kb_flag = 0;
812                                 
813                         } else if (strchr("!,:;{}", c) && (varcode == LM_TC_TEX||was_macro)) {
814                                 mathcursor->insert(c, LM_TC_TEX);
815                                 if (c == '{') {
816                                         mathcursor->insert('}', LM_TC_TEX);
817                                         mathcursor->Left();
818                                 }
819                                 mathcursor->clearLastCode();
820                                 //             varcode = LM_TC_MIN;
821                         } else if (c == '_' && varcode == LM_TC_TEX) {
822                                 mathcursor->insert(c, LM_TC_SPECIAL);
823                                 mathcursor->clearLastCode();
824                                 //             varcode = LM_TC_MIN;
825                         } else if ('0' <= c && c <= '9' && (varcode == LM_TC_TEX||was_macro)) {
826                                 mathcursor->MacroModeOpen();
827                                 mathcursor->clearLastCode();
828                                 mathcursor->insert(c, LM_TC_MIN);
829                         } else if (('0' <= c && c <= '9') || strchr(";:!|[]().,?", c)) {
830                                 MathTextCodes code = mathcursor->getLastCode();
831                                 if (code != LM_TC_TEXTRM)
832                                         code = LM_TC_CONST;
833                                 mathcursor->insert(c, code);
834                         } else if (strchr("+/-*<>=", c)) {
835                                 MathTextCodes code = mathcursor->getLastCode();
836                                 if (code != LM_TC_TEXTRM)
837                                         code = LM_TC_BOP;
838                                 mathcursor->insert(c, code);
839                         } else if (strchr(latex_special_chars, c) && c != '_') {
840                                 MathTextCodes code = mathcursor->getLastCode();
841                                 if (code != LM_TC_TEXTRM)
842                                         code = LM_TC_SPECIAL;
843                                 mathcursor->insert(c, code);
844                         } else if (c == '_' || c == '^') {
845                                 char s[2];
846                                 s[0] = c;
847                                 s[1] = 0;
848                                 mathcursor->Interpret(s);
849                         } else if (c == ' ') {
850                                 if (!varcode) { 
851                                         MathTextCodes f = (mathcursor->getLastCode()) ?
852                                                 mathcursor->getLastCode() :
853                                                 mathcursor->nextCode();
854                                         varcode = MathIsAlphaFont(f) ? f : LM_TC_VAR;
855                                 }
856                                 
857                                 if (varcode == LM_TC_TEXTRM)
858                                         mathcursor->insert(c, LM_TC_TEXTRM);
859                                 else if (was_macro)
860                                         mathcursor->MacroModeClose();
861                                 else if (mathcursor->pop())
862                                         mathcursor->plainRight();
863                                 else {
864                                         // this would not work if the inset is in an table!
865                                         //bv->text->cursorRight(bv, true);
866                                         result = FINISHED;
867                                 }
868                         } else if (c == '\'' || c == '@') {
869                                 mathcursor->insert(c, LM_TC_VAR);
870                         } else if (c == '\\') {
871                                 if (was_macro)
872                                         mathcursor->MacroModeClose();
873                                 bv->owner()->message(_("TeX mode"));
874                                 mathcursor->setLastCode(LM_TC_TEX);
875                         }
876                         updateLocal(bv, true);
877                 } else if (action == LFUN_MATH_PANEL) {
878                         result = UNDISPATCHED;
879                 } else {
880                         lyxerr << "Closed by action " << action << endl;
881                         result =  FINISHED;
882                 }
883         }
884
885         mathcursor->normalize();
886
887         if (was_macro != mathcursor->InMacroMode()
888                                 && action >= 0 && action != LFUN_BACKSPACE) 
889                 updateLocal(bv, true);
890         
891         if (mathcursor->Selection() || was_selection)
892                 toggleInsetSelection(bv);
893
894         if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
895             result == UNDISPATCHED)
896                 showInsetCursor(bv);
897         else
898                 bv->unlockInset(this);
899
900         return result;  // original version
901 }
902
903
904
905 /* FIXME: math-greek-toggle seems to work OK, but math-greek doesn't turn
906  * on greek mode */
907 bool math_insert_greek(BufferView * bv, char c)
908 {
909         if (!bv->available())
910                 return false;
911
912         if (!isalpha(c))
913                 return false;
914
915         string tmp;
916         tmp = c;
917         if (!bv->theLockingInset() || bv->theLockingInset()->isTextInset()) {
918                 int greek_kb_flag_save = greek_kb_flag;
919                 InsetFormula * new_inset = new InsetFormula();
920                 bv->beforeChange(bv->text);
921                 if (!bv->insertInset(new_inset)) {
922                         delete new_inset;
923                         return false;
924                 }
925                 //Update(1);//BUG
926                 new_inset->edit(bv, 0, 0, 0);
927                 new_inset->localDispatch(bv, LFUN_SELFINSERT, tmp);
928                 if (greek_kb_flag_save < 2) {
929                         bv->unlockInset(new_inset); // bv->theLockingInset());
930                         bv->text->cursorRight(bv, true);
931                 }
932         } else
933                 if (bv->theLockingInset()->lyxCode() == Inset::MATH_CODE ||
934                                 bv->theLockingInset()->lyxCode() == Inset::MATHMACRO_CODE)
935                         static_cast<InsetFormula*>(bv->theLockingInset())->localDispatch(bv, LFUN_SELFINSERT, tmp);
936                 else
937                         lyxerr << "Math error: attempt to write on a wrong "
938                                 "class of inset." << endl;
939         return true;
940 }
941
942
943
944 Inset::Code InsetFormulaBase::lyxCode() const
945 {
946         return Inset::MATH_CODE;
947 }
948
949
950 LyXFont const InsetFormulaBase::convertFont(LyXFont const & f) const
951 {
952         // We have already discussed what was here
953         LyXFont font(f);
954 #ifndef NO_LATEX
955         font.setLatex(LyXFont::OFF);
956 #endif
957         return font;
958 }
959
960 MathInset * InsetFormulaBase::par() const
961 {
962         return par_;
963 }
964
965
966 void mathDispatchCreation(BufferView * bv, string const & arg, bool display)
967 {
968         if (bv->available()) {
969 // Feature "Read math inset from selection" disabled.
970 //              // use selection if available..
971 //              string sel;
972 //              if (action == LFUN_MATH_IMPORT_SELECTION)
973 //                      sel = "";
974 //              else
975 //                      sel = bv->getLyXText()->selectionAsString(bv->buffer());
976
977                         InsetFormula * f;
978 //              if (sel.empty()) {
979                                 f = new InsetFormula;
980                                 if (openNewInset(bv, f)) {
981                                         // don't do that also for LFUN_MATH_MODE unless you want end up with
982                                         // always changing to mathrm when opening an inlined inset
983                                         // -- I really hate "LyXfunc overloading"...
984                                         if (display)
985                                                 f->localDispatch(bv, LFUN_MATH_DISPLAY, string());
986                                         f->localDispatch(bv, LFUN_INSERT_MATH, arg);
987                                 }
988 //              } else {
989 //                      f = new InsetFormula(sel);
990 //                      bv->getLyXText()->cutSelection(bv);
991 //                      openNewInset(bv, f);
992 //              }
993         }
994         bv->owner()->getLyXFunc()->setMessage(N_("Math editor mode"));
995 }
996
997 void mathDispatchMathDisplay(BufferView * bv, string const & arg)
998 {
999         mathDispatchCreation(bv, arg, true);
1000 }
1001         
1002 void mathDispatchMathMode(BufferView * bv, string const & arg)
1003 {
1004         mathDispatchCreation(bv, arg, false);
1005 }
1006
1007 void mathDispatchMathImportSelection(BufferView * bv, string const & arg)
1008 {
1009         mathDispatchCreation(bv, arg, true);
1010 }
1011
1012 void mathDispatchMathMacro(BufferView * bv, string const & arg)
1013 {
1014         if (bv->available()) {
1015                 if (arg.empty())
1016                         bv->owner()->getLyXFunc()->setErrorMessage(N_("Missing argument"));
1017                 else {
1018                         string s(arg);
1019                         string const s1 = token(s, ' ', 1);
1020                         int const na = s1.empty() ? 0 : lyx::atoi(s1);
1021                         openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
1022                 }
1023         }
1024 }
1025
1026 void mathDispatchMathDelim(BufferView * bv, string const & arg)
1027 {          
1028         if (bv->available()) { 
1029                 if (openNewInset(bv, new InsetFormula))
1030                         bv->theLockingInset()->localDispatch(bv, LFUN_MATH_DELIM, arg);
1031         }
1032 }          
1033
1034
1035 void mathDispatchInsertMatrix(BufferView * bv, string const & arg)
1036 {          
1037         if (bv->available()) { 
1038                 if (openNewInset(bv, new InsetFormula))
1039                         bv->theLockingInset()->localDispatch(bv, LFUN_INSERT_MATRIX, arg);
1040         }
1041 }          
1042
1043 void mathDispatchInsertMath(BufferView * bv, string const & arg)
1044 {
1045         if (bv->available()) {
1046                 if (arg.size() && arg[0] == '\\')
1047                         openNewInset(bv, new InsetFormula(arg));
1048                 else
1049                         mathDispatchMathMode(bv, arg);
1050         }
1051 }
1052