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