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