]> git.lyx.org Git - lyx.git/blob - src/mathed/formulabase.C
946541d850df7d4bfd171a522328fa9a871dcfec
[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         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]
369                 << "Used InsetFormulaBase::InsetKeyPress." << endl;
370 }
371
372
373
374 UpdatableInset::RESULT
375 InsetFormulaBase::localDispatch(BufferView * bv, kb_action action,
376                             string const & arg)
377 {
378         //lyxerr << "InsetFormulaBase::LocalDispatch: act: " << action
379         //      << " arg: '" << arg << "' cursor: " << mathcursor << "\n";
380
381         if (!mathcursor) 
382                 return UNDISPATCHED;
383
384         MathTextCodes varcode = LM_TC_MIN;
385         bool was_macro = mathcursor->InMacroMode();
386         bool sel = false;
387         bool was_selection = mathcursor->Selection();
388         RESULT result = DISPATCHED;
389
390         hideInsetCursor(bv);
391
392         if (mathcursor->getLastCode() == LM_TC_TEX)
393                 varcode = LM_TC_TEX;
394
395         mathcursor->normalize();
396
397         switch (action) {
398
399                 // --- Cursor Movements ---------------------------------------------
400
401         case LFUN_RIGHTSEL:
402                 sel = true; // fall through...
403
404         case LFUN_RIGHT:
405                 result = DISPATCH_RESULT(mathcursor->Right(sel));
406                 updateLocal(bv, false);
407                 break;
408
409
410         case LFUN_LEFTSEL:
411                 sel = true; // fall through
412
413         case LFUN_LEFT:
414                 result = DISPATCH_RESULT(mathcursor->Left(sel));
415                 updateLocal(bv, false);
416                 break;
417
418
419         case LFUN_UPSEL:
420                 sel = true;
421
422         case LFUN_UP:
423                 result = DISPATCH_RESULT(mathcursor->Up(sel));
424                 updateLocal(bv, false);
425                 break;
426
427
428         case LFUN_DOWNSEL:
429                 sel = true;
430
431         case LFUN_DOWN:
432                 result = DISPATCH_RESULT(mathcursor->Down(sel));
433                 updateLocal(bv, false);
434                 break;
435
436         case LFUN_HOME:
437                 mathcursor->Home();
438                 updateLocal(bv, false);
439                 break;
440
441         case LFUN_END:
442                 mathcursor->End();
443                 updateLocal(bv, false);
444                 break;
445
446         case LFUN_DELETE_LINE_FORWARD:
447                 bv->lockedInsetStoreUndo(Undo::DELETE);
448                 mathcursor->DelLine();
449                 updateLocal(bv, true);
450                 break;
451
452         case LFUN_TAB:
453                 mathcursor->idxNext();
454                 updateLocal(bv, false);
455                 break;
456
457         case LFUN_SHIFT_TAB:
458                 mathcursor->idxPrev();
459                 updateLocal(bv, false);
460                 break;
461
462         case LFUN_TABINSERT:
463                 bv->lockedInsetStoreUndo(Undo::EDIT);
464                 mathcursor->splitCell();
465                 updateLocal(bv, true);
466                 break;
467
468         case LFUN_BACKSPACE:
469                 // if (!mathcursor->InMacroMode() && mathcursor->pos() == 0)
470                 if (mathcursor->pos() == 0) {
471                         bv->lockedInsetStoreUndo(Undo::DELETE);
472                         mathcursor->pullArg(false);
473                         bv->updateInset(this, true);
474                         break;
475                 }
476                 if (mathcursor->InMacroMode())
477                         mathcursor->Left();
478                 else
479                         mathcursor->plainLeft();
480                 // fall through...
481
482         case LFUN_DELETE:
483                 bv->lockedInsetStoreUndo(Undo::DELETE);
484                 if (mathcursor->pos() == mathcursor->array().size()) 
485                         mathcursor->pullArg(true);
486                 else
487                         mathcursor->Delete();
488                 bv->updateInset(this, true);
489                 break;
490
491                 //    case LFUN_GETXY:
492                 //      sprintf(dispatch_buffer, "%d %d",);
493                 //      dispatch_result = dispatch_buffer;
494                 //      break;
495         case LFUN_SETXY:
496         {
497                 lyxerr << "LFUN_SETXY broken!\n";
498                 int x;
499                 int y;
500                 int x1;
501                 int y1;
502                 istringstream is(arg.c_str());
503                 is >> x >> y;
504                 par_->GetXY(x1, y1);
505                 mathcursor->SetPos(x1 + x, y1 + y);
506                 updateLocal(bv, false);
507         }
508         break;
509
510                 // cursor selection ---------------------------- 
511
512         case LFUN_PASTE:
513                 if (was_macro)
514                         mathcursor->MacroModeClose();
515                 bv->lockedInsetStoreUndo(Undo::INSERT);
516                 mathcursor->SelPaste();
517                 updateLocal(bv, true);
518                 break;
519
520         case LFUN_CUT:
521                 bv->lockedInsetStoreUndo(Undo::DELETE);
522                 mathcursor->SelCut();
523                 updateLocal(bv, true);
524                 break;
525
526         case LFUN_COPY:
527                 mathcursor->SelCopy();
528                 break;
529
530         case LFUN_HOMESEL:
531         case LFUN_ENDSEL:
532         case LFUN_WORDRIGHTSEL:
533         case LFUN_WORDLEFTSEL:
534                 break;
535
536                 // --- accented characters ------------------------------
537
538         case LFUN_UMLAUT:     handleAccent(bv, "ddot", LM_ddot); break;
539         case LFUN_CIRCUMFLEX: handleAccent(bv, "hat", LM_hat); break;
540         case LFUN_GRAVE:      handleAccent(bv, "grave", LM_grave); break;
541         case LFUN_ACUTE:      handleAccent(bv, "acute", LM_acute); break;
542         case LFUN_TILDE:      handleAccent(bv, "tilde", LM_tilde); break;
543         case LFUN_MACRON:     handleAccent(bv, "bar", LM_bar); break;
544         case LFUN_DOT:        handleAccent(bv, "dot", LM_dot); break;
545         case LFUN_CARON:      handleAccent(bv, "check", LM_check); break;
546         case LFUN_BREVE:      handleAccent(bv, "breve", LM_breve); break;
547         case LFUN_VECTOR:     handleAccent(bv, "vec", LM_vec); break;
548
549                 // Greek mode
550         case LFUN_GREEK:
551                 if (!greek_kb_flag) {
552                         greek_kb_flag = 1;
553                         bv->owner()->message(_("Math greek mode on"));
554                 } else
555                         greek_kb_flag = 0;
556                 break;
557
558                 // Greek keyboard
559         case LFUN_GREEK_TOGGLE:
560                 greek_kb_flag = greek_kb_flag ? 0 : 2;
561                 if (greek_kb_flag)
562                         bv->owner()->message(_("Math greek keyboard on"));
563                 else
564                         bv->owner()->message(_("Math greek keyboard off"));
565                 break;
566
567                 //  Math fonts
568         case LFUN_BOLD:    handleFont(bv, LM_TC_BF); break;
569         case LFUN_SANS:    handleFont(bv, LM_TC_SF); break;
570         case LFUN_EMPH:    handleFont(bv, LM_TC_CAL); break;
571         case LFUN_ROMAN:   handleFont(bv, LM_TC_RM); break;
572         case LFUN_CODE:    handleFont(bv, LM_TC_TT); break;
573         case LFUN_DEFAULT: handleFont(bv, LM_TC_VAR); break;
574
575         case LFUN_MATH_MODE:
576                 handleFont(bv, LM_TC_TEXTRM);
577                 //bv->owner()->message(_("math text mode toggled"));
578                 break;
579
580 #ifndef NO_LATEX
581         case LFUN_TEX:
582                 if (!mathcursor->Selection()) {
583                         mathcursor->handleFont(LM_TC_TEX);
584                         //bv->owner()->message(_("TeX mode toggled"));
585                 }
586                 break;
587 #endif
588
589         case LFUN_MATH_LIMITS:
590                 bv->lockedInsetStoreUndo(Undo::INSERT);
591                 if (mathcursor->toggleLimits())
592                         updateLocal(bv, true);
593                 break;
594
595         case LFUN_MATH_SIZE:
596                 if (!arg.empty()) {
597                         bv->lockedInsetStoreUndo(Undo::INSERT);
598                         latexkeys const * l = in_word_set(arg);
599                         mathcursor->SetSize(MathStyles(l ? l->id : static_cast<unsigned int>(-1)));
600                         updateLocal(bv, true);
601                 }
602                 break;
603
604         case LFUN_INSERT_MATRIX:
605                 if (!arg.empty()) {
606                         bv->lockedInsetStoreUndo(Undo::INSERT);
607                         mathcursor->Interpret("matrix " + arg);
608                         updateLocal(bv, true);
609                 }
610                 break;
611
612         case LFUN_INSERT_MATH:
613                 if (!arg.empty()) {
614                         bv->lockedInsetStoreUndo(Undo::INSERT);
615                         mathcursor->Interpret(arg);
616                         updateLocal(bv, true);
617                 }
618                 break;
619
620         case LFUN_MATH_DELIM:
621         {
622                 bv->lockedInsetStoreUndo(Undo::INSERT);
623                 static const string vdelim("(){}[]./|");
624                 //lyxerr << "formulabase::LFUN_MATH_DELIM, arg: '" << arg << "'\n";
625
626                 if (arg.empty())
627                         break;
628
629                 // try to read integers first
630                 int ilt = '(';
631                 int irt = '.';
632                 istringstream is(arg.c_str());
633                 is >> ilt >> irt;
634
635                 if (!is) { // ok, the beasties are no integers... try something else
636                         ilt = '(';
637                         irt = '.';
638
639                         istringstream is(arg.c_str());
640                         string lt;
641                         string rt;
642                         is >> lt >> rt;
643                         //lyxerr << "formulabase::LFUN_MATH_DELIM, lt: '" << lt << "'\n";
644                         //lyxerr << "formulabase::LFUN_MATH_DELIM, rt: '" << rt << "'\n";
645
646                         if (lt.size() > 1) {
647                                 latexkeys const * l = in_word_set(lt);
648                                 if (l)
649                                         ilt = l->id;
650                         } else if (vdelim.find(lt[0]) != string::npos)
651                                         ilt = lt[0];
652
653                         if (rt.size() > 1) {
654                                 latexkeys const * l = in_word_set(rt);
655                                 if (l)
656                                         irt = l->id;
657                         } else if (vdelim.find(rt[0]) != string::npos)
658                                         irt = rt[0];
659                 }
660
661                 handleDelim(bv, ilt, irt);
662                 updateLocal(bv, true);
663                 break;
664         }
665
666         case LFUN_PROTECTEDSPACE:
667                 bv->lockedInsetStoreUndo(Undo::INSERT);
668                 mathcursor->insert(new MathSpaceInset(1));
669                 updateLocal(bv, true);
670                 break;
671
672         case LFUN_UNDO:
673                 bv->owner()->message(_("Invalid action in math mode!"));
674                 break;
675
676
677         case LFUN_MATH_HALIGN:
678         {
679                 bv->lockedInsetStoreUndo(Undo::INSERT);
680                 lyxerr << "handling halign '" << arg << "'\n";
681                 int idx;
682                 MathArrayInset * p = matrixpar(idx);
683                 if (!p)
684                         break; 
685                 p->halign(arg.size() ? arg[0] : 'c', p->col(idx));
686                 updateLocal(bv, true);
687                 break;
688         }
689
690         case LFUN_MATH_VALIGN:
691         {
692                 bv->lockedInsetStoreUndo(Undo::INSERT);
693                 lyxerr << "handling valign '" << arg << "'\n";
694                 int idx;
695                 MathArrayInset * p = matrixpar(idx);
696                 if (!p)
697                         break; 
698                 p->valign(arg.size() ? arg[0] : 'c');
699                 updateLocal(bv, true);
700                 break;
701         }
702
703         case LFUN_MATH_ROW_INSERT:
704         {
705                 bv->lockedInsetStoreUndo(Undo::INSERT);
706                 int idx;
707                 MathArrayInset * p = matrixpar(idx);
708                 lyxerr << " calling LFUN_MATH_ROW_INSERT on " << p << endl;
709                 if (!p)
710                         break; 
711                 p->addRow(p->row(idx));
712                 updateLocal(bv, true);
713                 break;
714         }
715
716         case LFUN_MATH_ROW_DELETE:
717         {
718                 bv->lockedInsetStoreUndo(Undo::INSERT);
719                 int idx;
720                 MathArrayInset * p = matrixpar(idx);
721                 lyxerr << " calling LFUN_MATH_ROW_DELETE on " << p << endl;
722                 if (!p)
723                         break; 
724                 p->delRow(p->row(idx));
725                 updateLocal(bv, true);
726                 break;
727         }
728
729         case LFUN_MATH_COLUMN_INSERT:
730         {
731                 bv->lockedInsetStoreUndo(Undo::INSERT);
732                 int idx;
733                 MathArrayInset * p = matrixpar(idx);
734                 if (!p)
735                         break; 
736                 p->addCol(p->col(idx));
737                 updateLocal(bv, true);
738                 break;
739         }
740
741         case LFUN_MATH_COLUMN_DELETE:
742         {
743                 bv->lockedInsetStoreUndo(Undo::INSERT);
744                 int idx;
745                 MathArrayInset * p = matrixpar(idx);
746                 if (!p)
747                         break; 
748                 p->delCol(p->col(idx));
749                 updateLocal(bv, true);
750                 break;
751         }
752
753         case LFUN_EXEC_COMMAND:
754                 result = UNDISPATCHED;
755                 break;
756
757         default:
758                 if ((action == -1 || action == LFUN_SELFINSERT) && !arg.empty()) {
759                         unsigned char c = arg[0];
760
761                         lyxerr << "Action: " << action << endl;
762                         
763                         lyxerr << "char: '" << c << "'  int: " << int(c) << endl;
764                         //owner_->getIntl()->getTrans().TranslateAndInsert(c, lt);      
765                         //lyxerr << "trans: '" << c << "'  int: " << int(c) << endl;
766                         bv->lockedInsetStoreUndo(Undo::INSERT);
767
768                         if (c == 0) {      // Dead key, do nothing
769                                 //lyxerr << "deadkey" << endl;
770                                 break;
771                         }
772
773                         if (isalpha(c)) {
774                                 if (mathcursor->getLastCode() == LM_TC_TEX) {
775                                         mathcursor->MacroModeOpen();
776                                         mathcursor->clearLastCode();
777                                         varcode = LM_TC_MIN;
778                                 } else if (!varcode) {          
779                                         MathTextCodes f = mathcursor->getLastCode() ?
780                                                 mathcursor->getLastCode() :
781                                                 mathcursor->nextCode();
782                                         varcode = MathIsAlphaFont(f) ?
783                                                 static_cast<MathTextCodes>(f) :
784                                                 LM_TC_VAR;
785                                 }
786                                 
787                                 //           lyxerr << "Varcode << vardoce;
788                                 MathTextCodes char_code = varcode;
789                                 if (greek_kb_flag) {
790                                         char greek[26] =
791                                         {'A', 'B', 'X',  0 , 'E',  0 ,  0 , 'H', 'I',  0 ,
792                                          'K',  0 , 'M', 'N', 'O',  0 ,  0 , 'P',  0 , 'T',
793                                          'Y',  0,   0,   0,   0 , 'Z' };
794                                         
795                                         if ('A' <= c && c <= 'Z' && greek[c - 'A']) {
796                                                 char_code = LM_TC_RM;
797                                                 c = greek[c - 'A'];
798                                         } else
799                                                 char_code = LM_TC_SYMB;
800                                 }
801                                 
802                                 mathcursor->insert(c, char_code);
803                                 
804                                 if (greek_kb_flag && char_code == LM_TC_RM )
805                                         mathcursor->setLastCode(LM_TC_VAR);
806                                 
807                                 varcode = LM_TC_MIN;
808                                 
809                                 if (greek_kb_flag < 2)
810                                         greek_kb_flag = 0;
811                                 
812                         } else if (strchr("!,:;{}", c) && (varcode == LM_TC_TEX||was_macro)) {
813                                 mathcursor->insert(c, LM_TC_TEX);
814                                 if (c == '{') {
815                                         mathcursor->insert('}', LM_TC_TEX);
816                                         mathcursor->Left();
817                                 }
818                                 mathcursor->clearLastCode();
819                                 //             varcode = LM_TC_MIN;
820                         } else if (c == '_' && varcode == LM_TC_TEX) {
821                                 mathcursor->insert(c, LM_TC_SPECIAL);
822                                 mathcursor->clearLastCode();
823                                 //             varcode = LM_TC_MIN;
824                         } else if ('0' <= c && c <= '9' && (varcode == LM_TC_TEX||was_macro)) {
825                                 mathcursor->MacroModeOpen();
826                                 mathcursor->clearLastCode();
827                                 mathcursor->insert(c, LM_TC_MIN);
828                         } else if (('0' <= c && c <= '9') || strchr(";:!|[]().,?", c)) {
829                                 MathTextCodes code = mathcursor->getLastCode();
830                                 if (code != LM_TC_TEXTRM)
831                                         code = LM_TC_CONST;
832                                 mathcursor->insert(c, code);
833                         } else if (strchr("+/-*<>=", c)) {
834                                 MathTextCodes code = mathcursor->getLastCode();
835                                 if (code != LM_TC_TEXTRM)
836                                         code = LM_TC_BOP;
837                                 mathcursor->insert(c, code);
838                         } else if (strchr(latex_special_chars, c) && c != '_') {
839                                 MathTextCodes code = mathcursor->getLastCode();
840                                 if (code != LM_TC_TEXTRM)
841                                         code = LM_TC_SPECIAL;
842                                 mathcursor->insert(c, code);
843                         } else if (c == '_' || c == '^') {
844                                 char s[2];
845                                 s[0] = c;
846                                 s[1] = 0;
847                                 mathcursor->Interpret(s);
848                         } else if (c == ' ') {
849                                 if (!varcode) { 
850                                         MathTextCodes f = (mathcursor->getLastCode()) ?
851                                                 mathcursor->getLastCode() :
852                                                 mathcursor->nextCode();
853                                         varcode = MathIsAlphaFont(f) ? f : LM_TC_VAR;
854                                 }
855                                 
856                                 if (varcode == LM_TC_TEXTRM)
857                                         mathcursor->insert(c, LM_TC_TEXTRM);
858                                 else if (was_macro)
859                                         mathcursor->MacroModeClose();
860                                 else if (mathcursor->pop())
861                                         mathcursor->plainRight();
862                                 else {
863                                         // this would not work if the inset is in an table!
864                                         //bv->text->cursorRight(bv, true);
865                                         result = FINISHED;
866                                 }
867                         } else if (c == '\'' || c == '@') {
868                                 mathcursor->insert(c, LM_TC_VAR);
869                         } else if (c == '\\') {
870                                 if (was_macro)
871                                         mathcursor->MacroModeClose();
872                                 bv->owner()->message(_("TeX mode"));
873                                 mathcursor->setLastCode(LM_TC_TEX);
874                         }
875                         updateLocal(bv, true);
876                 } else if (action == LFUN_MATH_PANEL) {
877                         result = UNDISPATCHED;
878                 } else {
879                         lyxerr << "Closed by action " << action << endl;
880                         result =  FINISHED;
881                 }
882         }
883
884         mathcursor->normalize();
885
886         if (was_macro != mathcursor->InMacroMode()
887                                 && action >= 0 && action != LFUN_BACKSPACE) 
888                 updateLocal(bv, true);
889         
890         if (mathcursor->Selection() || was_selection)
891                 toggleInsetSelection(bv);
892
893         if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
894             result == UNDISPATCHED)
895                 showInsetCursor(bv);
896         else
897                 bv->unlockInset(this);
898
899         return result;  // original version
900 }
901
902
903
904 /* FIXME: math-greek-toggle seems to work OK, but math-greek doesn't turn
905  * on greek mode */
906 bool math_insert_greek(BufferView * bv, char c)
907 {
908         if (!bv->available())
909                 return false;
910
911         if (!isalpha(c))
912                 return false;
913
914         string tmp;
915         tmp = c;
916         if (!bv->theLockingInset() || bv->theLockingInset()->isTextInset()) {
917                 int greek_kb_flag_save = greek_kb_flag;
918                 InsetFormula * new_inset = new InsetFormula();
919                 bv->beforeChange(bv->text);
920                 if (!bv->insertInset(new_inset)) {
921                         delete new_inset;
922                         return false;
923                 }
924                 //Update(1);//BUG
925                 new_inset->edit(bv, 0, 0, 0);
926                 new_inset->localDispatch(bv, LFUN_SELFINSERT, tmp);
927                 if (greek_kb_flag_save < 2) {
928                         bv->unlockInset(new_inset); // bv->theLockingInset());
929                         bv->text->cursorRight(bv, true);
930                 }
931         } else
932                 if (bv->theLockingInset()->lyxCode() == Inset::MATH_CODE ||
933                                 bv->theLockingInset()->lyxCode() == Inset::MATHMACRO_CODE)
934                         static_cast<InsetFormula*>(bv->theLockingInset())->localDispatch(bv, LFUN_SELFINSERT, tmp);
935                 else
936                         lyxerr << "Math error: attempt to write on a wrong "
937                                 "class of inset." << endl;
938         return true;
939 }
940
941
942
943 Inset::Code InsetFormulaBase::lyxCode() const
944 {
945         return Inset::MATH_CODE;
946 }
947
948
949 LyXFont const InsetFormulaBase::convertFont(LyXFont const & f) const
950 {
951         // We have already discussed what was here
952         LyXFont font(f);
953 #ifndef NO_LATEX
954         font.setLatex(LyXFont::OFF);
955 #endif
956         return font;
957 }
958
959 MathInset * InsetFormulaBase::par() const
960 {
961         return par_;
962 }
963
964
965 void mathDispatchCreation(BufferView * bv, string const & arg, bool display)
966 {
967         if (bv->available()) {
968 // Feature "Read math inset from selection" disabled.
969 //              // use selection if available..
970 //              string sel;
971 //              if (action == LFUN_MATH_IMPORT_SELECTION)
972 //                      sel = "";
973 //              else
974 //                      sel = bv->getLyXText()->selectionAsString(bv->buffer());
975
976                         InsetFormula * f;
977 //              if (sel.empty()) {
978                                 f = new InsetFormula;
979                                 if (openNewInset(bv, f)) {
980                                         // don't do that also for LFUN_MATH_MODE unless you want end up with
981                                         // always changing to mathrm when opening an inlined inset
982                                         // -- I really hate "LyXfunc overloading"...
983                                         if (display)
984                                                 f->localDispatch(bv, LFUN_MATH_DISPLAY, string());
985                                         f->localDispatch(bv, LFUN_INSERT_MATH, arg);
986                                 }
987 //              } else {
988 //                      f = new InsetFormula(sel);
989 //                      bv->getLyXText()->cutSelection(bv);
990 //                      openNewInset(bv, f);
991 //              }
992         }
993         bv->owner()->getLyXFunc()->setMessage(N_("Math editor mode"));
994 }
995
996 void mathDispatchMathDisplay(BufferView * bv, string const & arg)
997 {
998         mathDispatchCreation(bv, arg, true);
999 }
1000         
1001 void mathDispatchMathMode(BufferView * bv, string const & arg)
1002 {
1003         mathDispatchCreation(bv, arg, false);
1004 }
1005
1006 void mathDispatchMathImportSelection(BufferView * bv, string const & arg)
1007 {
1008         mathDispatchCreation(bv, arg, true);
1009 }
1010
1011 void mathDispatchMathMacro(BufferView * bv, string const & arg)
1012 {
1013         if (bv->available()) {
1014                 if (arg.empty())
1015                         bv->owner()->getLyXFunc()->setErrorMessage(N_("Missing argument"));
1016                 else {
1017                         string s(arg);
1018                         string const s1 = token(s, ' ', 1);
1019                         int const na = s1.empty() ? 0 : lyx::atoi(s1);
1020                         openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
1021                 }
1022         }
1023 }
1024
1025 void mathDispatchMathDelim(BufferView * bv, string const & arg)
1026 {          
1027         if (bv->available()) { 
1028                 if (openNewInset(bv, new InsetFormula))
1029                         bv->theLockingInset()->localDispatch(bv, LFUN_MATH_DELIM, arg);
1030         }
1031 }          
1032
1033
1034 void mathDispatchInsertMatrix(BufferView * bv, string const & arg)
1035 {          
1036         if (bv->available()) { 
1037                 if (openNewInset(bv, new InsetFormula))
1038                         bv->theLockingInset()->localDispatch(bv, LFUN_INSERT_MATRIX, arg);
1039         }
1040 }          
1041
1042 void mathDispatchInsertMath(BufferView * bv, string const & arg)
1043 {
1044         if (bv->available()) {
1045                 if (arg.size() && arg[0] == '\\')
1046                         openNewInset(bv, new InsetFormula(arg));
1047                 else
1048                         mathDispatchMathMode(bv, arg);
1049         }
1050 }
1051