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