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