]> git.lyx.org Git - lyx.git/blob - src/mathed/formulabase.C
fix 'off by one' cursor position when handling simultaneous super- and
[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                 // if (!mathcursor->inMacroMode() && mathcursor->pos() == 0)
451                 if (mathcursor->pos() == 0) {
452                         bv->lockedInsetStoreUndo(Undo::DELETE);
453                         mathcursor->pullArg(false);
454                         bv->updateInset(this, true);
455                         break;
456                 }
457                 if (mathcursor->inMacroMode())
458                         mathcursor->left();
459                 else
460                         mathcursor->plainLeft();
461                 // fall through...
462
463         case LFUN_DELETE:
464                 bv->lockedInsetStoreUndo(Undo::DELETE);
465                 if (mathcursor->pos() == mathcursor->array().size()) 
466                         mathcursor->pullArg(true);
467                 else
468                         mathcursor->erase();
469                 bv->updateInset(this, true);
470                 break;
471
472                 //    case LFUN_GETXY:
473                 //      sprintf(dispatch_buffer, "%d %d",);
474                 //      dispatch_result = dispatch_buffer;
475                 //      break;
476         case LFUN_SETXY:
477         {
478                 lyxerr << "LFUN_SETXY broken!\n";
479                 int x;
480                 int y;
481                 int x1;
482                 int y1;
483                 istringstream is(arg.c_str());
484                 is >> x >> y;
485                 par()->getXY(x1, y1);
486                 mathcursor->setPos(x1 + x, y1 + y);
487                 updateLocal(bv, false);
488         }
489         break;
490
491
492         case LFUN_PASTE:
493                 if (was_macro)
494                         mathcursor->macroModeClose();
495                 bv->lockedInsetStoreUndo(Undo::INSERT);
496                 mathcursor->selPaste();
497                 updateLocal(bv, true);
498                 break;
499
500         case LFUN_CUT:
501                 bv->lockedInsetStoreUndo(Undo::DELETE);
502                 mathcursor->selCut();
503                 updateLocal(bv, true);
504                 break;
505
506         case LFUN_COPY:
507                 mathcursor->selCopy();
508                 break;
509
510         case LFUN_HOMESEL:
511         case LFUN_ENDSEL:
512         case LFUN_WORDRIGHTSEL:
513         case LFUN_WORDLEFTSEL:
514                 break;
515
516                 // --- accented characters ------------------------------
517
518         case LFUN_UMLAUT:     handleAccent(bv, "ddot"); break;
519         case LFUN_CIRCUMFLEX: handleAccent(bv, "hat"); break;
520         case LFUN_GRAVE:      handleAccent(bv, "grave"); break;
521         case LFUN_ACUTE:      handleAccent(bv, "acute"); break;
522         case LFUN_TILDE:      handleAccent(bv, "tilde"); break;
523         case LFUN_MACRON:     handleAccent(bv, "bar"); break;
524         case LFUN_DOT:        handleAccent(bv, "dot"); break;
525         case LFUN_CARON:      handleAccent(bv, "check"); break;
526         case LFUN_BREVE:      handleAccent(bv, "breve"); break;
527         case LFUN_VECTOR:     handleAccent(bv, "vec"); break;
528
529                 // Greek mode
530         case LFUN_GREEK:
531                 if (!greek_kb_flag) {
532                         greek_kb_flag = 1;
533                         bv->owner()->message(_("Math greek mode on"));
534                 } else
535                         greek_kb_flag = 0;
536                 break;
537
538                 // Greek keyboard
539         case LFUN_GREEK_TOGGLE:
540                 greek_kb_flag = greek_kb_flag ? 0 : 2;
541                 if (greek_kb_flag)
542                         bv->owner()->message(_("Math greek keyboard on"));
543                 else
544                         bv->owner()->message(_("Math greek keyboard off"));
545                 break;
546
547                 //  Math fonts
548         case LFUN_BOLD:    handleFont(bv, LM_TC_BF); break;
549         case LFUN_SANS:    handleFont(bv, LM_TC_SF); break;
550         case LFUN_EMPH:    handleFont(bv, LM_TC_CAL); break;
551         case LFUN_ROMAN:   handleFont(bv, LM_TC_RM); break;
552         case LFUN_CODE:    handleFont(bv, LM_TC_TT); break;
553         case LFUN_DEFAULT: handleFont(bv, LM_TC_VAR); break;
554
555         case LFUN_MATH_MODE:
556                 handleFont(bv, LM_TC_TEXTRM);
557                 //bv->owner()->message(_("math text mode toggled"));
558                 break;
559
560         case LFUN_MATH_LIMITS:
561                 bv->lockedInsetStoreUndo(Undo::INSERT);
562                 if (mathcursor->toggleLimits())
563                         updateLocal(bv, true);
564                 break;
565
566         case LFUN_MATH_SIZE:
567                 if (!arg.empty()) {
568                         bv->lockedInsetStoreUndo(Undo::INSERT);
569                         latexkeys const * l = in_word_set(arg);
570                         mathcursor->setSize(MathStyles(l ? l->id : static_cast<unsigned int>(-1)));
571                         updateLocal(bv, true);
572                 }
573                 break;
574
575         case LFUN_INSERT_MATRIX:
576                 if (!arg.empty()) {
577                         bv->lockedInsetStoreUndo(Undo::INSERT);
578                         mathcursor->interpret("matrix " + arg);
579                         updateLocal(bv, true);
580                 }
581                 break;
582
583         case LFUN_INSERT_MATH:
584                 if (!arg.empty()) {
585                         bv->lockedInsetStoreUndo(Undo::INSERT);
586                         mathcursor->interpret(arg);
587                         updateLocal(bv, true);
588                 }
589                 break;
590
591         case LFUN_MATH_SPACE:
592         {
593                 bv->lockedInsetStoreUndo(Undo::EDIT);
594                 MathSpaceInset * p = mathcursor->prevSpaceInset();
595                 if (p) 
596                         p->incSpace();
597                 else
598                         mathcursor->insert(new MathSpaceInset(1));
599                 updateLocal(bv, true);
600                 break;
601         }
602
603         case LFUN_MATH_DELIM:
604         {
605                 bv->lockedInsetStoreUndo(Undo::INSERT);
606                 static const string vdelim("(){}[]./|");
607                 //lyxerr << "formulabase::LFUN_MATH_DELIM, arg: '" << arg << "'\n";
608
609                 if (arg.empty())
610                         break;
611
612                 // try to read integers first
613                 int ilt = '(';
614                 int irt = '.';
615                 istringstream is(arg.c_str());
616                 is >> ilt >> irt;
617
618                 if (!is) { // ok, the beasties are no integers... try something else
619                         ilt = '(';
620                         irt = '.';
621
622                         istringstream is(arg.c_str());
623                         string lt;
624                         string rt;
625                         is >> lt >> rt;
626                         //lyxerr << "formulabase::LFUN_MATH_DELIM, lt: '" << lt << "'\n";
627                         //lyxerr << "formulabase::LFUN_MATH_DELIM, rt: '" << rt << "'\n";
628
629                         if (lt.size() > 1) {
630                                 latexkeys const * l = in_word_set(lt);
631                                 if (l)
632                                         ilt = l->id;
633                         } else if (vdelim.find(lt[0]) != string::npos)
634                                         ilt = lt[0];
635
636                         if (rt.size() > 1) {
637                                 latexkeys const * l = in_word_set(rt);
638                                 if (l)
639                                         irt = l->id;
640                         } else if (vdelim.find(rt[0]) != string::npos)
641                                         irt = rt[0];
642                 }
643
644                 handleDelim(bv, ilt, irt);
645                 updateLocal(bv, true);
646                 break;
647         }
648
649         case LFUN_PROTECTEDSPACE:
650                 //lyxerr << " called LFUN_PROTECTEDSPACE\n";
651                 bv->lockedInsetStoreUndo(Undo::INSERT);
652                 mathcursor->insert(new MathSpaceInset(1));
653                 updateLocal(bv, true);
654                 break;
655
656         case LFUN_UNDO:
657                 bv->owner()->message(_("Invalid action in math mode!"));
658                 break;
659
660
661         case LFUN_MATH_HALIGN:
662         {
663                 bv->lockedInsetStoreUndo(Undo::INSERT);
664                 lyxerr << "handling halign '" << arg << "'\n";
665                 int idx;
666                 MathArrayInset * p = matrixpar(idx);
667                 if (!p)
668                         break; 
669                 p->halign(arg.size() ? arg[0] : 'c', p->col(idx));
670                 updateLocal(bv, true);
671                 break;
672         }
673
674         case LFUN_MATH_VALIGN:
675         {
676                 bv->lockedInsetStoreUndo(Undo::INSERT);
677                 lyxerr << "handling valign '" << arg << "'\n";
678                 int idx;
679                 MathArrayInset * p = matrixpar(idx);
680                 if (!p)
681                         break; 
682                 p->valign(arg.size() ? arg[0] : 'c');
683                 updateLocal(bv, true);
684                 break;
685         }
686
687         case LFUN_MATH_ROW_INSERT:
688         {
689                 bv->lockedInsetStoreUndo(Undo::INSERT);
690                 int idx;
691                 MathArrayInset * p = matrixpar(idx);
692                 lyxerr << " calling LFUN_MATH_ROW_INSERT on " << p << endl;
693                 if (!p)
694                         break; 
695                 p->addRow(p->row(idx));
696                 updateLocal(bv, true);
697                 break;
698         }
699
700         case LFUN_MATH_ROW_DELETE:
701         {
702                 bv->lockedInsetStoreUndo(Undo::INSERT);
703                 int idx;
704                 MathArrayInset * p = matrixpar(idx);
705                 lyxerr << " calling LFUN_MATH_ROW_DELETE on " << p << endl;
706                 if (!p)
707                         break; 
708                 p->delRow(p->row(idx));
709                 updateLocal(bv, true);
710                 break;
711         }
712
713         case LFUN_MATH_COLUMN_INSERT:
714         {
715                 bv->lockedInsetStoreUndo(Undo::INSERT);
716                 int idx;
717                 MathArrayInset * p = matrixpar(idx);
718                 if (!p)
719                         break; 
720                 p->addCol(p->col(idx));
721                 updateLocal(bv, true);
722                 break;
723         }
724
725         case LFUN_MATH_COLUMN_DELETE:
726         {
727                 bv->lockedInsetStoreUndo(Undo::INSERT);
728                 int idx;
729                 MathArrayInset * p = matrixpar(idx);
730                 if (!p)
731                         break; 
732                 p->delCol(p->col(idx));
733                 updateLocal(bv, true);
734                 break;
735         }
736
737         case LFUN_EXEC_COMMAND:
738                 result = UNDISPATCHED;
739                 break;
740
741         default:
742                 if ((action == -1 || action == LFUN_SELFINSERT) && !arg.empty()) {
743                         unsigned char c = arg[0];
744
745                         lyxerr << "Action: " << action << endl;
746                         
747                         lyxerr << "char: '" << c << "'  int: " << int(c) << endl;
748                         //owner_->getIntl()->getTrans().TranslateAndInsert(c, lt);      
749                         //lyxerr << "trans: '" << c << "'  int: " << int(c) << endl;
750                         bv->lockedInsetStoreUndo(Undo::INSERT);
751
752                         if (c == 0) {      // Dead key, do nothing
753                                 //lyxerr << "deadkey" << endl;
754                                 break;
755                         }
756
757                         if (isalpha(c)) {
758                                 if (mathcursor->getLastCode() == LM_TC_TEX) {
759                                         mathcursor->macroModeOpen();
760                                         mathcursor->clearLastCode();
761                                         varcode = LM_TC_MIN;
762                                 } else if (!varcode) {          
763                                         MathTextCodes f = mathcursor->getLastCode() ?
764                                                 mathcursor->getLastCode() :
765                                                 mathcursor->nextCode();
766                                         varcode = MathIsAlphaFont(f) ?
767                                                 static_cast<MathTextCodes>(f) :
768                                                 LM_TC_VAR;
769                                 }
770                                 
771                                 //           lyxerr << "Varcode << vardoce;
772                                 MathTextCodes char_code = varcode;
773                                 if (greek_kb_flag) {
774                                         char greek[26] =
775                                         {'A', 'B', 'X',  0 , 'E',  0 ,  0 , 'H', 'I',  0 ,
776                                          'K',  0 , 'M', 'N', 'O',  0 ,  0 , 'P',  0 , 'T',
777                                          0,  0,   0,   0,   0 , 'Z' };
778                                         
779                                         if ('A' <= c && c <= 'Z' && greek[c - 'A']) {
780                                                 char_code = LM_TC_RM;
781                                                 c = greek[c - 'A'];
782                                         } else
783                                                 char_code = LM_TC_SYMB;
784                                 }
785                                 
786                                 mathcursor->insert(c, char_code);
787                                 
788                                 if (greek_kb_flag && char_code == LM_TC_RM)
789                                         mathcursor->setLastCode(LM_TC_VAR);
790                                 
791                                 varcode = LM_TC_MIN;
792                                 
793                                 if (greek_kb_flag < 2)
794                                         greek_kb_flag = 0;
795                                 
796                         } else if (strchr("!,:;{}", c) && (varcode == LM_TC_TEX||was_macro)) {
797                                 mathcursor->insert(c, LM_TC_TEX);
798                                 if (c == '{') {
799                                         mathcursor->insert('}', LM_TC_TEX);
800                                         mathcursor->left();
801                                 }
802                                 mathcursor->clearLastCode();
803                                 //             varcode = LM_TC_MIN;
804                         } else if (c == '_' && varcode == LM_TC_TEX) {
805                                 mathcursor->insert(c, LM_TC_SPECIAL);
806                                 mathcursor->clearLastCode();
807                                 //             varcode = LM_TC_MIN;
808                         } else if ('0' <= c && c <= '9' && (varcode == LM_TC_TEX||was_macro)) {
809                                 mathcursor->macroModeOpen();
810                                 mathcursor->clearLastCode();
811                                 mathcursor->insert(c, LM_TC_MIN);
812                         } else if (('0' <= c && c <= '9') || strchr(";:!|[]().,?", c)) {
813                                 MathTextCodes code = mathcursor->getLastCode();
814                                 if (code != LM_TC_TEXTRM)
815                                         code = LM_TC_CONST;
816                                 mathcursor->insert(c, code);
817                         } else if (strchr("+/-*<>=", c)) {
818                                 MathTextCodes code = mathcursor->getLastCode();
819                                 if (code != LM_TC_TEXTRM)
820                                         code = LM_TC_BOP;
821                                 mathcursor->insert(c, code);
822                         } else if (strchr(latex_special_chars, c) && c != '_') {
823                                 MathTextCodes code = mathcursor->getLastCode();
824                                 if (code != LM_TC_TEXTRM)
825                                         code = LM_TC_SPECIAL;
826                                 mathcursor->insert(c, code);
827                         } else if (c == '_' || c == '^') {
828                                 char s[2];
829                                 s[0] = c;
830                                 s[1] = 0;
831                                 mathcursor->interpret(s);
832                         } else if (c == ' ') {
833                                 if (!varcode) { 
834                                         MathTextCodes f = (mathcursor->getLastCode()) ?
835                                                 mathcursor->getLastCode() :
836                                                 mathcursor->nextCode();
837                                         varcode = MathIsAlphaFont(f) ? f : LM_TC_VAR;
838                                 }
839                                 
840                                 if (varcode == LM_TC_TEXTRM)
841                                         mathcursor->insert(c, LM_TC_TEXTRM);
842                                 else if (was_macro)
843                                         mathcursor->macroModeClose();
844                                 else if (mathcursor->pop())
845                                         mathcursor->plainRight();
846                                 else {
847                                         // this would not work if the inset is in an table!
848                                         //bv->text->cursorRight(bv, true);
849                                         result = FINISHED;
850                                 }
851                         } else if (c == '\'' || c == '@') {
852                                 mathcursor->insert(c, LM_TC_VAR);
853                         } else if (c == '\\') {
854                                 if (was_macro)
855                                         mathcursor->macroModeClose();
856                                 bv->owner()->message(_("TeX mode"));
857                                 mathcursor->setLastCode(LM_TC_TEX);
858                         }
859                         updateLocal(bv, true);
860                 } else if (action == LFUN_MATH_PANEL) {
861                         result = UNDISPATCHED;
862                 } else {
863                         lyxerr << "Closed by action " << action << endl;
864                         result =  FINISHED;
865                 }
866         }
867
868         mathcursor->normalize();
869
870         if (was_macro != mathcursor->inMacroMode()
871                                 && action >= 0 && action != LFUN_BACKSPACE) 
872                 updateLocal(bv, true);
873         
874         if (mathcursor->selection() || was_selection)
875                 toggleInsetSelection(bv);
876
877         if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
878             result == UNDISPATCHED)
879                 showInsetCursor(bv);
880         else
881                 bv->unlockInset(this);
882
883         return result;  // original version
884 }
885
886
887 Inset::Code InsetFormulaBase::lyxCode() const
888 {
889         return Inset::MATH_CODE;
890 }
891
892
893 void mathDispatchCreation(BufferView * bv, string const & arg, bool display)
894 {
895         if (bv->available()) {
896 // Feature "Read math inset from selection" disabled.
897 //              // use selection if available..
898 //              string sel;
899 //              if (action == LFUN_MATH_IMPORT_SELECTION)
900 //                      sel = "";
901 //              else
902 //                      sel = bv->getLyXText()->selectionAsString(bv->buffer());
903
904                         InsetFormula * f;
905 //              if (sel.empty()) {
906                                 f = new InsetFormula;
907                                 if (openNewInset(bv, f)) {
908                                         // don't do that also for LFUN_MATH_MODE unless you want end up with
909                                         // always changing to mathrm when opening an inlined inset
910                                         // -- I really hate "LyXfunc overloading"...
911                                         if (display)
912                                                 f->localDispatch(bv, LFUN_MATH_DISPLAY, string());
913                                         f->localDispatch(bv, LFUN_INSERT_MATH, arg);
914                                 }
915 //              } else {
916 //                      f = new InsetFormula(sel);
917 //                      bv->getLyXText()->cutSelection(bv);
918 //                      openNewInset(bv, f);
919 //              }
920         }
921         bv->owner()->getLyXFunc()->setMessage(N_("Math editor mode"));
922 }
923
924 void mathDispatchMathDisplay(BufferView * bv, string const & arg)
925 {
926         mathDispatchCreation(bv, arg, true);
927 }
928         
929 void mathDispatchMathMode(BufferView * bv, string const & arg)
930 {
931         mathDispatchCreation(bv, arg, false);
932 }
933
934 void mathDispatchMathImportSelection(BufferView * bv, string const & arg)
935 {
936         mathDispatchCreation(bv, arg, true);
937 }
938
939 void mathDispatchMathMacro(BufferView * bv, string const & arg)
940 {
941         if (bv->available()) {
942                 if (arg.empty())
943                         bv->owner()->getLyXFunc()->setErrorMessage(N_("Missing argument"));
944                 else {
945                         string s(arg);
946                         string const s1 = token(s, ' ', 1);
947                         int const na = s1.empty() ? 0 : lyx::atoi(s1);
948                         openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
949                 }
950         }
951 }
952
953 void mathDispatchMathDelim(BufferView * bv, string const & arg)
954 {          
955         if (bv->available()) { 
956                 if (openNewInset(bv, new InsetFormula))
957                         bv->theLockingInset()->localDispatch(bv, LFUN_MATH_DELIM, arg);
958         }
959 }          
960
961
962 void mathDispatchInsertMatrix(BufferView * bv, string const & arg)
963 {          
964         if (bv->available()) { 
965                 if (openNewInset(bv, new InsetFormula))
966                         bv->theLockingInset()->localDispatch(bv, LFUN_INSERT_MATRIX, arg);
967         }
968 }          
969
970 void mathDispatchInsertMath(BufferView * bv, string const & arg)
971 {
972         if (bv->available()) {
973                 if (arg.size() && arg[0] == '\\')
974                         openNewInset(bv, new InsetFormula(arg));
975                 else
976                         mathDispatchMathMode(bv, arg);
977         }
978 }
979