]> git.lyx.org Git - lyx.git/blob - src/mathed/formulabase.C
* LyXView: the accessor methods now return a reference to the member
[lyx.git] / src / mathed / formulabase.C
1 /*
2 *  File:        formulabase.C
3 *  Purpose:     Implementation of common parts of the LyX  math insets
4 *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
5 *  Created:     January 1996
6 *
7 *  Copyright: 1996-1998 Alejandro Aguilar Sierra
8 *
9 *  Version: 0.4, Lyx project.
10 *
11 *   You are free to use and modify this code under the terms of
12 *   the GNU General Public Licence version 2 or later.
13 */
14
15 #include <config.h>
16 #include <fstream>
17
18 #include "Lsstream.h"
19 #include "support/LAssert.h"
20
21 #ifdef __GNUG__
22 #pragma implementation
23 #endif
24
25 #include "formula.h"
26 #include "formulamacro.h"
27 #include "lyxrc.h"
28 #include "funcrequest.h"
29 #include "BufferView.h"
30 #include "lyxtext.h"
31 #include "lyxfunc.h"
32 #include "gettext.h"
33 #include "LaTeXFeatures.h"
34 #include "debug.h"
35 #include "math_support.h"
36 #include "math_metricsinfo.h"
37 #include "support/lstrings.h"
38 #include "frontends/LyXView.h"
39 #include "frontends/font_metrics.h"
40 #include "frontends/mouse_state.h"
41 #include "Lsstream.h"
42 #include "math_arrayinset.h"
43 #include "math_charinset.h"
44 #include "math_deliminset.h"
45 #include "math_cursor.h"
46 #include "math_factory.h"
47 #include "math_fontinset.h"
48 #include "math_hullinset.h"
49 #include "math_iterator.h"
50 #include "math_macrotable.h"
51 #include "math_parser.h"
52 #include "math_pos.h"
53 #include "math_spaceinset.h"
54 #include "undo_funcs.h"
55 #include "textpainter.h"
56 #include "frontends/Dialogs.h"
57 #include "intl.h"
58 #include "insets/insetcommandparams.h"
59 #include "ref_inset.h"
60
61 using std::endl;
62 using std::ostream;
63 using std::vector;
64 using std::abs;
65
66 MathCursor * mathcursor = 0;
67
68
69 namespace {
70
71 // local global
72 int first_x;
73 int first_y;
74
75
76
77 bool openNewInset(BufferView * bv, UpdatableInset * new_inset)
78 {
79         if (!bv->insertInset(new_inset)) {
80                 delete new_inset;
81                 return false;
82         }
83         new_inset->edit(bv, true);
84         return true;
85 }
86
87
88 } // namespace anon
89
90
91
92 InsetFormulaBase::InsetFormulaBase()
93         : font_(), xo_(0), yo_(0)
94 {
95         // This is needed as long the math parser is not re-entrant
96         initMath();
97         //lyxerr << "sizeof MathInset: " << sizeof(MathInset) << "\n";
98         //lyxerr << "sizeof MathMetricsInfo: " << sizeof(MathMetricsInfo) << "\n";
99         //lyxerr << "sizeof MathCharInset: " << sizeof(MathCharInset) << "\n";
100         //lyxerr << "sizeof LyXFont: " << sizeof(LyXFont) << "\n";
101 }
102
103
104 // simply scrap this function if you want
105 void InsetFormulaBase::mutateToText()
106 {
107 #if 0
108         // translate to latex
109         ostringstream os;
110         latex(NULL, os, false, false);
111         string str = os.str();
112
113         // insert this text
114         LyXText * lt = view_->getLyXText();
115         string::const_iterator cit = str.begin();
116         string::const_iterator end = str.end();
117         for (; cit != end; ++cit)
118                 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
119
120         // remove ourselves
121         //view_->owner()->getLyXFunc().dispatch(LFUN_ESCAPE);
122 #endif
123 }
124
125
126 void InsetFormulaBase::handleFont
127         (BufferView * bv, string const & arg, string const & font)
128 {
129         bv->lockedInsetStoreUndo(Undo::EDIT);
130         bool sel = mathcursor->selection();
131         if (sel)
132                 updateLocal(bv, true);
133         mathcursor->handleNest(createMathInset(font));
134         mathcursor->insert(arg);
135         if (!sel)
136                 updateLocal(bv, false);
137 }
138
139
140 // Check if uses AMS macros
141 void InsetFormulaBase::validate(LaTeXFeatures &) const
142 {}
143
144
145 void InsetFormulaBase::metrics(BufferView * bv, LyXFont const & f) const
146 {
147         font_ = f;
148         metrics(bv);
149 }
150
151
152 void InsetFormulaBase::metrics(BufferView * bv) const
153 {
154         if (bv)
155                 view_ = bv->owner()->view();
156         MathMetricsInfo mi;
157         mi.base.style = LM_ST_TEXT;
158         mi.base.font  = font_;
159         mi.base.font.setColor(LColor::math);
160         par()->metrics(mi);
161 }
162
163
164 string const InsetFormulaBase::editMessage() const
165 {
166         return _("Math editor mode");
167 }
168
169
170 void InsetFormulaBase::edit(BufferView * bv, int x, int y, mouse_button::state)
171 {
172         if (!bv->lockInset(this))
173                 lyxerr[Debug::MATHED] << "Cannot lock inset!!!" << endl;
174         releaseMathCursor(bv);
175         mathcursor = new MathCursor(this, true);
176         metrics(bv);
177         mathcursor->setPos(x, y);
178         //lyxerr << "setting pos to " << x << "," << y << "\n";
179
180         // if that is removed, we won't get the magenta box when entering an
181         // inset for the first time
182         bv->updateInset(this, false);
183 }
184
185
186 void InsetFormulaBase::edit(BufferView * bv, bool front)
187 {
188         if (!bv->lockInset(this))
189                 lyxerr << "Cannot lock math inset in edit call!\n";
190         releaseMathCursor(bv);
191         mathcursor = new MathCursor(this, front);
192         metrics(bv);
193         bv->updateInset(this, false);
194 }
195
196
197 void InsetFormulaBase::insetUnlock(BufferView * bv)
198 {
199         if (mathcursor) {
200                 if (mathcursor->inMacroMode()) {
201                         mathcursor->macroModeClose();
202                         updateLocal(bv, true);
203                 }
204                 releaseMathCursor(bv);
205         }
206         generatePreview();
207         bv->updateInset(this, false);
208 }
209
210
211 void InsetFormulaBase::getCursorPos(BufferView *, int & x, int & y) const
212 {
213         // calling metrics here destroys the cached xo,yo positions e.g. in
214         // MathParboxinset. And it would be too expensive anyway...
215         //metrics(bv);
216         mathcursor->getPos(x, y);
217         //x -= xo_;
218         y -= yo_;
219         //lyxerr << "getCursorPos: " << x << " " << y << "\n";
220 }
221
222
223 void InsetFormulaBase::toggleInsetCursor(BufferView * bv)
224 {
225         //lyxerr << "toggleInsetCursor: " << isCursorVisible() << "\n";
226         if (isCursorVisible())
227                 hideInsetCursor(bv);
228         else
229                 showInsetCursor(bv);
230 }
231
232
233 void InsetFormulaBase::showInsetCursor(BufferView * bv, bool)
234 {
235         if (isCursorVisible())
236                 return;
237         fitInsetCursor(bv);
238         int x, y, asc, des;
239         getCursorPos(bv, x, y);
240         math_font_max_dim(font_, asc, des);
241         bv->showLockedInsetCursor(x, y, asc, des);
242         setCursorVisible(true);
243         //lyxerr << "showInsetCursor: " << x << " " << y << "\n";
244 }
245
246
247 void InsetFormulaBase::hideInsetCursor(BufferView * bv)
248 {
249         if (!isCursorVisible())
250                 return;
251         bv->hideLockedInsetCursor();
252         setCursorVisible(false);
253         //lyxerr << "hideInsetCursor: \n";
254 }
255
256
257 void InsetFormulaBase::fitInsetCursor(BufferView * bv) const
258 {
259         if (!mathcursor)
260                 return;
261         int x, y, asc, des;
262         math_font_max_dim(font_, asc, des);
263         getCursorPos(bv, x, y);
264         //y += yo_;
265         //lyxerr << "fitInsetCursor: x: " << x << " y: " << y << " yo: " << yo_ << "\n";
266         bv->fitLockedInsetCursor(x, y, asc, des);
267 }
268
269
270 void InsetFormulaBase::toggleInsetSelection(BufferView * bv)
271 {
272         if (mathcursor)
273                 bv->updateInset(this, false);
274 }
275
276
277 vector<string> const InsetFormulaBase::getLabelList() const
278 {
279   return vector<string>();
280 }
281
282
283 void InsetFormulaBase::updateLocal(BufferView * bv, bool dirty)
284 {
285         bv->updateInset(this, dirty);
286 }
287
288
289 bool InsetFormulaBase::insetButtonRelease(BufferView * bv,
290         int x, int y, mouse_button::state button)
291 {
292         if (!mathcursor)
293                 return false;
294
295         //lyxerr << "insetButtonRelease: " << x << " " << y << "\n";
296         hideInsetCursor(bv);
297         showInsetCursor(bv);
298         bv->updateInset(this, false);
299
300         if (button == mouse_button::button3) {
301                 // try to dispatch to enclosed insets first
302                 if (mathcursor->dispatch(FuncRequest(LFUN_MOUSE_RELEASE, x, y, 3)))
303                         return true;
304
305                 // launch math panel for right mouse button
306                 bv->owner()->getDialogs().showMathPanel();
307                 return true;
308         }
309
310         if (button == mouse_button::button1) {
311                 // try to dispatch to enclosed insets first
312                 if (mathcursor->dispatch(FuncRequest(LFUN_MOUSE_RELEASE, x, y, 1)))
313                         return true;
314
315                 // try to set the cursor
316                 //delete mathcursor;
317                 //mathcursor = new MathCursor(this, x == 0);
318                 //metrics(bv);
319                 //mathcursor->setPos(x + xo_, y + yo_);
320                 return true;
321         }
322         return false;
323 }
324
325
326 void InsetFormulaBase::insetButtonPress(BufferView * bv,
327                                         int x, int y, mouse_button::state button)
328 {
329         //lyxerr << "insetButtonPress: "
330         //      << x << " " << y << " but: " << button << "\n";
331         //lyxerr << "formula: ";
332         //par()->dump();
333
334         releaseMathCursor(bv);
335         mathcursor = new MathCursor(this, x == 0);
336
337         if (button == mouse_button::button1) {
338                 // just set the cursor here
339                 //lyxerr << "setting cursor\n";
340                 metrics(bv);
341                 first_x = x;
342                 first_y = y;
343                 mathcursor->selClear();
344                 mathcursor->setPos(x + xo_, y + yo_);
345
346                 if (mathcursor->dispatch(FuncRequest(LFUN_MOUSE_PRESS, x, y, 1))) {
347                         //delete mathcursor;
348                         return;
349                 }
350
351         }
352         if (button == mouse_button::button3) {
353                 if (mathcursor->dispatch(FuncRequest(LFUN_MOUSE_PRESS, x, y, 3))) {
354                         //delete mathcursor;
355                         return;
356                 }
357         }
358         bv->updateInset(this, false);
359 }
360
361
362 void InsetFormulaBase::insetMotionNotify(BufferView * bv,
363         int x, int y, mouse_button::state button)
364 {
365         if (!mathcursor)
366                 return;
367
368         if (button == mouse_button::button1)
369                 if (mathcursor->dispatch(FuncRequest(LFUN_MOUSE_MOTION, x, y, 1)))
370                         return;
371
372         if (button == mouse_button::button3)
373                 if (mathcursor->dispatch(FuncRequest(LFUN_MOUSE_MOTION, x, y, 3)))
374                         return;
375
376         if (abs(x - first_x) < 2 && abs(y - first_y) < 2) {
377                 //lyxerr << "insetMotionNotify: ignored\n";
378                 return;
379         }
380         first_x = x;
381         first_y = y;
382
383         if (!mathcursor->selection())
384                 mathcursor->selStart();
385
386         //lyxerr << "insetMotionNotify: " << x + xo_ << ' ' << y + yo_
387         //      << ' ' << button << "\n";
388         hideInsetCursor(bv);
389         mathcursor->setPos(x + xo_, y + yo_);
390         showInsetCursor(bv);
391         bv->updateInset(this, false);
392 }
393
394
395 UpdatableInset::RESULT
396 InsetFormulaBase::localDispatch(BufferView * bv, FuncRequest const & ev)
397 {
398         //lyxerr << "InsetFormulaBase::localDispatch: act: " << action
399         //      << " arg: '" << arg
400         //      << "' cursor: " << mathcursor << "\n";
401
402         if (!mathcursor)
403                 return UNDISPATCHED;
404
405         string argument    = ev.argument;
406         RESULT result      = DISPATCHED;
407         bool sel           = false;
408         bool was_macro     = mathcursor->inMacroMode();
409         bool was_selection = mathcursor->selection();
410
411         hideInsetCursor(bv);
412
413         mathcursor->normalize();
414         mathcursor->touch();
415
416         switch (ev.action) {
417
418         case LFUN_WORDRIGHTSEL:
419         case LFUN_RIGHTSEL:
420                 sel = true; // fall through...
421         case LFUN_RIGHT:
422                 result = mathcursor->right(sel) ? DISPATCHED : FINISHED_RIGHT;
423                 //lyxerr << "calling scroll 20\n";
424                 //scroll(bv, 20);
425                 updateLocal(bv, false);
426                 // write something to the minibuffer
427                 //bv->owner()->message(mathcursor->info());
428                 break;
429
430         case LFUN_WORDLEFTSEL:
431         case LFUN_LEFTSEL:
432                 sel = true; // fall through
433         case LFUN_LEFT:
434                 result = mathcursor->left(sel) ? DISPATCHED : FINISHED;
435                 updateLocal(bv, false);
436                 break;
437
438         case LFUN_UPSEL:
439                 sel = true; // fall through
440         case LFUN_UP:
441                 result = mathcursor->up(sel) ? DISPATCHED : FINISHED_UP;
442                 updateLocal(bv, false);
443                 break;
444
445         case LFUN_DOWNSEL:
446                 sel = true; // fall through
447         case LFUN_DOWN:
448                 result = mathcursor->down(sel) ? DISPATCHED : FINISHED_DOWN;
449                 updateLocal(bv, false);
450                 break;
451
452         case LFUN_HOMESEL:
453                 sel = true; // fall through
454         case LFUN_HOME:
455                 result = mathcursor->home(sel) ? DISPATCHED : FINISHED;
456                 updateLocal(bv, false);
457                 break;
458
459         case LFUN_ENDSEL:
460                 sel = true; // fall through
461         case LFUN_END:
462                 result = mathcursor->end(sel) ? DISPATCHED : FINISHED_RIGHT;
463                 updateLocal(bv, false);
464                 break;
465
466         case LFUN_PRIORSEL:
467         case LFUN_PRIOR:
468                 result = FINISHED_UP;
469                 updateLocal(bv, false);
470                 break;
471
472         case LFUN_NEXTSEL:
473         case LFUN_NEXT:
474                 result = FINISHED_DOWN;
475                 updateLocal(bv, false);
476                 break;
477
478         case LFUN_DELETE_LINE_FORWARD:
479                 bv->lockedInsetStoreUndo(Undo::DELETE);
480                 mathcursor->delLine();
481                 updateLocal(bv, true);
482                 break;
483
484         case LFUN_TAB:
485                 mathcursor->idxNext();
486                 updateLocal(bv, false);
487                 break;
488
489         case LFUN_SHIFT_TAB:
490                 mathcursor->idxPrev();
491                 updateLocal(bv, false);
492                 break;
493
494         case LFUN_TABINSERT:
495                 bv->lockedInsetStoreUndo(Undo::EDIT);
496                 mathcursor->splitCell();
497                 updateLocal(bv, true);
498                 break;
499
500         case LFUN_DELETE_WORD_BACKWARD:
501         case LFUN_BACKSPACE:
502                 bv->lockedInsetStoreUndo(Undo::DELETE);
503                 mathcursor->backspace();
504                 updateLocal(bv, true);
505                 break;
506
507         case LFUN_DELETE_WORD_FORWARD:
508         case LFUN_DELETE:
509                 bv->lockedInsetStoreUndo(Undo::DELETE);
510                 mathcursor->erase();
511                 bv->updateInset(this, true);
512                 break;
513
514         //    case LFUN_GETXY:
515         //      sprintf(dispatch_buffer, "%d %d",);
516         //      dispatch_result = dispatch_buffer;
517         //      break;
518         case LFUN_SETXY: {
519                 lyxerr << "LFUN_SETXY broken!\n";
520                 int x = 0;
521                 int y = 0;
522                 istringstream is(ev.argument.c_str());
523                 is >> x >> y;
524                 mathcursor->setPos(x, y);
525                 updateLocal(bv, false);
526                 break;
527         }
528
529         case LFUN_PASTE:
530                 if (was_macro)
531                         mathcursor->macroModeClose();
532                 bv->lockedInsetStoreUndo(Undo::EDIT);
533                 mathcursor->selPaste();
534                 updateLocal(bv, true);
535                 break;
536
537         case LFUN_CUT:
538                 bv->lockedInsetStoreUndo(Undo::DELETE);
539                 mathcursor->selCut();
540                 updateLocal(bv, true);
541                 break;
542
543         case LFUN_COPY:
544                 mathcursor->selCopy();
545                 break;
546
547
548         // Special casing for superscript in case of LyX handling
549         // dead-keys:
550         case LFUN_CIRCUMFLEX:
551                 if (ev.argument.empty()) {
552                         // do superscript if LyX handles
553                         // deadkeys
554                         bv->lockedInsetStoreUndo(Undo::EDIT);
555                         mathcursor->script(true);
556                         updateLocal(bv, true);
557                 }
558                 break;
559
560         case LFUN_UMLAUT:
561         case LFUN_ACUTE:
562         case LFUN_GRAVE:
563         case LFUN_BREVE:
564         case LFUN_DOT:
565         case LFUN_MACRON:
566         case LFUN_CARON:
567         case LFUN_TILDE:
568         case LFUN_CEDILLA:
569         case LFUN_CIRCLE:
570         case LFUN_UNDERDOT:
571         case LFUN_TIE:
572         case LFUN_OGONEK:
573         case LFUN_HUNG_UMLAUT:
574                 break;
575
576         //  Math fonts
577         case LFUN_GREEK_TOGGLE: handleFont(bv, ev.argument, "lyxgreek"); break;
578         case LFUN_BOLD:         handleFont(bv, ev.argument, "textbf"); break;
579         case LFUN_SANS:         handleFont(bv, ev.argument, "textsf"); break;
580         case LFUN_EMPH:         handleFont(bv, ev.argument, "mathcal"); break;
581         case LFUN_ROMAN:        handleFont(bv, ev.argument, "mathrm"); break;
582         case LFUN_CODE:         handleFont(bv, ev.argument, "texttt"); break;
583         case LFUN_FRAK:         handleFont(bv, ev.argument, "mathfrak"); break;
584         case LFUN_ITAL:         handleFont(bv, ev.argument, "mathit"); break;
585         case LFUN_NOUN:         handleFont(bv, ev.argument, "mathbb"); break;
586         case LFUN_DEFAULT:      handleFont(bv, ev.argument, "textnormal"); break;
587         case LFUN_FREE:         handleFont(bv, ev.argument, "textrm"); break;
588
589         case LFUN_GREEK:
590                 handleFont(bv, ev.argument, "lyxgreek1");
591                 if (ev.argument.size())
592                         mathcursor->interpret(ev.argument);
593                 break;
594
595         case LFUN_MATH_MODE:
596                 if (mathcursor->currentMode()) {
597                         handleFont(bv, ev.argument, "textrm");
598                 } else {
599                         mathcursor->niceInsert(MathAtom(new MathHullInset("simple")));
600                         updateLocal(bv, true);
601                 }
602                 //bv->owner()->message(_("math text mode toggled"));
603                 break;
604
605         case LFUN_MATH_LIMITS:
606                 bv->lockedInsetStoreUndo(Undo::EDIT);
607                 if (mathcursor->toggleLimits())
608                         updateLocal(bv, true);
609                 break;
610
611         case LFUN_MATH_SIZE:
612 #if 0
613                 if (!arg.empty()) {
614                         bv->lockedInsetStoreUndo(Undo::EDIT);
615                         mathcursor->setSize(arg);
616                         updateLocal(bv, true);
617                 }
618 #endif
619                 break;
620
621         case LFUN_INSERT_MATRIX:
622                 if (!ev.argument.empty()) {
623                         bv->lockedInsetStoreUndo(Undo::EDIT);
624                         mathcursor->interpret("matrix " + ev.argument);
625                         updateLocal(bv, true);
626                 }
627                 break;
628
629         case LFUN_SUPERSCRIPT:
630         case LFUN_SUBSCRIPT:
631         {
632                 bv->lockedInsetStoreUndo(Undo::EDIT);
633                 mathcursor->script(ev.action == LFUN_SUPERSCRIPT);
634                 updateLocal(bv, true);
635                 break;
636         }
637
638         case LFUN_MATH_DELIM:
639         {
640                 //lyxerr << "formulabase::LFUN_MATH_DELIM, arg: '" << arg << "'\n";
641                 string ls;
642                 string rs = split(ev.argument, ls, ' ');
643                 // Reasonable default values
644                 if (ls.empty())
645                         ls = '(';
646                 if (rs.empty())
647                         rs = ')';
648
649                 bv->lockedInsetStoreUndo(Undo::EDIT);
650                 mathcursor->handleNest(MathAtom(new MathDelimInset(ls, rs)));
651                 updateLocal(bv, true);
652                 break;
653         }
654
655         case LFUN_PROTECTEDSPACE:
656         case LFUN_MATH_SPACE:
657                 bv->lockedInsetStoreUndo(Undo::EDIT);
658                 mathcursor->insert(MathAtom(new MathSpaceInset(",")));
659                 updateLocal(bv, true);
660                 break;
661
662         case LFUN_UNDO:
663                 bv->owner()->message(_("Invalid action in math mode!"));
664                 break;
665
666
667         case LFUN_MATH_HALIGN:
668         case LFUN_MATH_VALIGN:
669         case LFUN_MATH_ROW_INSERT:
670         case LFUN_MATH_ROW_DELETE:
671         case LFUN_MATH_COLUMN_INSERT:
672         case LFUN_MATH_COLUMN_DELETE:
673         {
674                 MathInset::idx_type idx = 0;
675                 MathGridInset * p = mathcursor ? mathcursor->enclosingGrid(idx) : 0;
676                 if (p) {
677                         mathcursor->popToEnclosingGrid();
678                         bv->lockedInsetStoreUndo(Undo::EDIT);
679                         char align = ev.argument.size() ? ev.argument[0] : 'c';
680                         switch (ev.action) {
681                                 case LFUN_MATH_HALIGN: p->halign(align, p->col(idx)); break;
682                                 case LFUN_MATH_VALIGN: p->valign(align); break;
683                                 case LFUN_MATH_ROW_INSERT: p->addRow(p->row(idx)); break;
684                                 case LFUN_MATH_ROW_DELETE: p->delRow(p->row(idx)); break;
685                                 case LFUN_MATH_COLUMN_INSERT: p->addFancyCol(p->col(idx)); break;
686                                 case LFUN_MATH_COLUMN_DELETE: p->delFancyCol(p->col(idx)); break;
687                                 default: ;
688                         }
689                         updateLocal(bv, true);
690                 }
691                 break;
692         }
693
694         case LFUN_EXEC_COMMAND:
695                 result = UNDISPATCHED;
696                 break;
697
698         case LFUN_INSET_ERT:
699                 // interpret this as if a backslash was typed
700                 bv->lockedInsetStoreUndo(Undo::EDIT);
701                 mathcursor->interpret('\\');
702                 updateLocal(bv, true);
703                 break;
704
705         case LFUN_BREAKPARAGRAPH:
706         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
707         case LFUN_BREAKPARAGRAPH_SKIP:
708                 argument = "\n";
709                 // fall through
710
711         case -1:
712         case LFUN_INSERT_MATH:
713         case LFUN_SELFINSERT:
714                 if (!argument.empty()) {
715                         bv->lockedInsetStoreUndo(Undo::EDIT);
716                         if (argument.size() == 1)
717                                 result = mathcursor->interpret(argument[0]) ? DISPATCHED : FINISHED_RIGHT;
718                         else
719                                 result = mathcursor->interpret(argument) ? DISPATCHED : FINISHED_RIGHT;
720                         updateLocal(bv, true);
721                 }
722                 break;
723
724         case LFUN_MATH_PANEL:
725                 result = UNDISPATCHED;
726                 break;
727
728         case LFUN_ESCAPE:
729                 if (mathcursor->selection())
730                         mathcursor->selClear();
731                 else
732                         result = UNDISPATCHED;
733                 break;
734
735         case LFUN_INSET_TOGGLE:
736                 mathcursor->insetToggle();
737                 updateLocal(bv, true);
738                 break;
739
740         case LFUN_REF_INSERT:
741                 //if (argument.empty()) {
742                 //      InsetCommandParams p("ref");
743                 //      owner_->getDialogs().createRef(p.getAsString());
744                 //} else {
745                 //      InsetCommandParams p;
746                 //      p.setFromString(argument);
747
748                 //      InsetRef * inset = new InsetRef(p, *buffer_);
749                 //      if (!insertInset(inset))
750                 //              delete inset;
751                 //      else
752                 //              updateInset(inset, true);
753                 //}
754                 //
755                 if (ev.argument.empty()) {
756                         InsetCommandParams p("ref");
757                         bv->owner()->getDialogs().createRef(p.getAsString());
758                 } else {
759                         //mathcursor->handleNest(new InsetRef2);
760                         //mathcursor->insert(arg);
761                         mathcursor->insert(MathAtom(new RefInset(ev.argument)));
762                 }
763                 updateLocal(bv, true);
764                 break;
765
766         default:
767                 result = UNDISPATCHED;
768         }
769
770         mathcursor->normalize();
771         mathcursor->touch();
772
773         lyx::Assert(mathcursor);
774
775         if (mathcursor->selection() || was_selection)
776                 toggleInsetSelection(bv);
777
778         if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
779             result == UNDISPATCHED) {
780                 fitInsetCursor(bv);
781                 showInsetCursor(bv);
782                 revealCodes(bv);
783         } else {
784                 releaseMathCursor(bv);
785                 bv->unlockInset(this);
786         }
787
788         return result;  // original version
789 }
790
791
792 void InsetFormulaBase::revealCodes(BufferView * bv) const
793 {
794         if (!mathcursor)
795                 return;
796         bv->owner()->message(mathcursor->info());
797
798 #if 0
799         // write something to the minibuffer
800         // translate to latex
801         mathcursor->markInsert();
802         ostringstream os;
803         write(NULL, os);
804         string str = os.str();
805         mathcursor->markErase();
806         string::size_type pos = 0;
807         string res;
808         for (string::iterator it = str.begin(); it != str.end(); ++it) {
809                 if (*it == '\n')
810                         res += ' ';
811                 else if (*it == '\0') {
812                         res += "  -X-  ";
813                         pos = it - str.begin();
814                 }
815                 else
816                         res += *it;
817         }
818         if (pos > 30)
819                 res = res.substr(pos - 30);
820         if (res.size() > 60)
821                 res = res.substr(0, 60);
822         bv->owner()->message(res);
823 #endif
824 }
825
826
827 Inset::Code InsetFormulaBase::lyxCode() const
828 {
829         return Inset::MATH_CODE;
830 }
831
832
833 int InsetFormulaBase::ylow() const
834 {
835         return yo_ - ascent(view(), font_);
836 }
837
838
839 int InsetFormulaBase::yhigh() const
840 {
841         return yo_ + descent(view(), font_);
842 }
843
844
845 int InsetFormulaBase::xlow() const
846 {
847         return xo_;
848 }
849
850
851 int InsetFormulaBase::xhigh() const
852 {
853         return xo_ + width(view(), font_);
854 }
855
856
857 /////////////////////////////////////////////////////////////////////
858
859
860 bool InsetFormulaBase::searchForward(BufferView * bv, string const & str,
861                                      bool, bool)
862 {
863 #ifdef WITH_WARNINGS
864 #warning pretty ugly
865 #endif
866         static InsetFormulaBase * lastformula = 0;
867         static MathIterator current = MathIterator(ibegin(par().nucleus()));
868         static MathArray ar;
869         static string laststr;
870
871         if (lastformula != this || laststr != str) {
872                 //lyxerr << "reset lastformula to " << this << "\n";
873                 lastformula = this;
874                 laststr = str;
875                 current = ibegin(par().nucleus());
876                 ar.clear();
877                 mathed_parse_cell(ar, str);
878         } else {
879                 ++current;
880         }
881         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
882
883         for (MathIterator it = current; it != iend(par().nucleus()); ++it) {
884                 if (it.cell().matchpart(ar, it.back().pos_)) {
885                         bv->unlockInset(bv->theLockingInset());
886                         if (!bv->lockInset(this)) {
887                                 lyxerr << "Cannot lock inset" << endl;
888                                 return false;
889                         }
890                         delete mathcursor;
891                         mathcursor = new MathCursor(this, true);
892                         metrics(bv);
893                         mathcursor->setSelection(it, ar.size());
894                         current = it;
895                         it.jump(ar.size());
896                         updateLocal(bv, false);
897                         return true;
898                 }
899         }
900
901         //lyxerr << "not found!\n";
902         lastformula = 0;
903         return false;
904 }
905
906
907 bool InsetFormulaBase::searchBackward(BufferView * bv, string const & what,
908                                       bool a, bool b)
909 {
910         lyxerr[Debug::MATHED] << "searching backward not implemented in mathed\n";
911         return searchForward(bv, what, a, b);
912 }
913
914
915 /////////////////////////////////////////////////////////////////////
916
917
918 void mathDispatchCreation(BufferView * bv, string const & arg, bool display)
919 {
920         if (!bv->available())
921                 return;
922
923         // use selection if available..
924         //string sel;
925         //if (action == LFUN_MATH_IMPORT_SELECTION)
926         //      sel = "";
927         //else
928
929         string sel = bv->getLyXText()->selectionAsString(bv->buffer(), false);
930
931         if (sel.empty()) {
932                 InsetFormula * f = new InsetFormula(bv);
933                 if (openNewInset(bv, f)) {
934                         f->mutate("simple");
935                         // don't do that also for LFUN_MATH_MODE unless you want end up with
936                         // always changing to mathrm when opening an inlined inset
937                         // -- I really hate "LyXfunc overloading"...
938                         if (display)
939                                 f->localDispatch(bv, FuncRequest(LFUN_MATH_DISPLAY));
940                         f->localDispatch(bv, FuncRequest(LFUN_INSERT_MATH, arg));
941                 }
942         } else {
943                 // create a macro if we see "\\newcommand" somewhere, and an ordinary
944                 // formula otherwise
945                 InsetFormulaBase * f;
946                 if (sel.find("\\newcommand") == string::npos &&
947                                 sel.find("\\def") == string::npos)
948                         f = new InsetFormula(sel);
949                 else
950                         f = new InsetFormulaMacro(sel);
951                 bv->getLyXText()->cutSelection(bv);
952                 openNewInset(bv, f);
953         }
954         bv->owner()->getLyXFunc().setMessage(N_("Math editor mode"));
955 }
956
957
958 void mathDispatchMathDisplay(BufferView * bv, string const & arg)
959 {
960         mathDispatchCreation(bv, arg, true);
961 }
962
963
964 void mathDispatchMathMode(BufferView * bv, string const & arg)
965 {
966         mathDispatchCreation(bv, arg, false);
967 }
968
969
970 void mathDispatchMathImportSelection(BufferView * bv, string const & arg)
971 {
972         mathDispatchCreation(bv, arg, true);
973 }
974
975
976 void mathDispatchMathMacro(BufferView * bv, string const & arg)
977 {
978         if (!bv->available())
979                 return;
980         if (arg.empty())
981                 bv->owner()->getLyXFunc().setErrorMessage(N_("Missing argument"));
982         else {
983                 string s = arg;
984                 string const s1 = token(s, ' ', 1);
985                 int const na = s1.empty() ? 0 : lyx::atoi(s1);
986                 openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
987         }
988 }
989
990
991 void mathDispatchMathDelim(BufferView * bv, string const & arg)
992 {
993         if (!bv->available())
994                 return;
995         InsetFormula * f = new InsetFormula(bv);
996         if (openNewInset(bv, f)) {
997                 f->mutate("simple");
998                 bv->theLockingInset()->localDispatch(bv, FuncRequest(LFUN_MATH_DELIM, arg));
999         }
1000 }
1001
1002
1003 void mathDispatchInsertMatrix(BufferView * bv, string const & arg)
1004 {
1005         if (!bv->available())
1006                 return;
1007         InsetFormula * f = new InsetFormula(bv);
1008         if (openNewInset(bv, f)) {
1009                 f->mutate("simple");
1010                 bv->theLockingInset()->localDispatch(bv, FuncRequest(LFUN_INSERT_MATRIX, arg));
1011         }
1012 }
1013
1014
1015 void mathDispatchInsertMath(BufferView * bv, string const & arg)
1016 {
1017         if (!bv->available())
1018                 return;
1019         InsetFormula * f = new InsetFormula(bv);
1020         if (openNewInset(bv, f)) {
1021                 f->mutate("simple");
1022     bv->theLockingInset()->localDispatch(bv, FuncRequest(LFUN_INSERT_MATH, arg));
1023         }
1024 }
1025
1026
1027 void mathDispatchGreek(BufferView * bv, string const & arg)
1028 {
1029         if (!bv->available())
1030                 return;
1031         InsetFormula * f = new InsetFormula(bv);
1032         if (openNewInset(bv, f)) {
1033                 f->mutate("simple");
1034                 bv->theLockingInset()->localDispatch(bv, FuncRequest(LFUN_GREEK, arg));
1035                 bv->unlockInset(f);
1036         }
1037 }
1038
1039
1040 void mathDispatch(BufferView *, kb_action, string const &)
1041 {}
1042
1043
1044 void mathDispatch(BufferView *, string const &)
1045 {}