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