]> git.lyx.org Git - lyx.git/blob - src/mathed/formulabase.C
more cursor up/down smoothing
[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 "gettext.h"
32 #include "LaTeXFeatures.h"
33 #include "debug.h"
34 #include "math_support.h"
35 #include "math_metricsinfo.h"
36 #include "support/lstrings.h"
37 #include "frontends/LyXView.h"
38 #include "frontends/font_metrics.h"
39 #include "frontends/mouse_state.h"
40 #include "Lsstream.h"
41 #include "math_arrayinset.h"
42 #include "math_charinset.h"
43 #include "math_deliminset.h"
44 #include "math_cursor.h"
45 #include "math_factory.h"
46 #include "math_fontinset.h"
47 #include "math_hullinset.h"
48 #include "math_iterator.h"
49 #include "math_macrotable.h"
50 #include "math_parser.h"
51 #include "math_pos.h"
52 #include "math_spaceinset.h"
53 #include "undo_funcs.h"
54 #include "textpainter.h"
55 #include "frontends/Dialogs.h"
56 #include "intl.h"
57 #include "insets/insetcommandparams.h"
58 #include "ref_inset.h"
59
60 using std::endl;
61 using std::ostream;
62 using std::vector;
63 using std::abs;
64
65 MathCursor * mathcursor = 0;
66
67
68 namespace {
69
70 // local global
71 int first_x;
72 int first_y;
73
74
75
76 bool openNewInset(BufferView * bv, UpdatableInset * new_inset)
77 {
78         if (!bv->insertInset(new_inset)) {
79                 delete new_inset;
80                 return false;
81         }
82         new_inset->edit(bv, true);
83         return true;
84 }
85
86
87 } // namespace anon
88
89
90
91 InsetFormulaBase::InsetFormulaBase()
92         : font_(), xo_(0), yo_(0)
93 {
94         // This is needed as long the math parser is not re-entrant
95         initMath();
96         //lyxerr << "sizeof MathInset: " << sizeof(MathInset) << "\n";
97         //lyxerr << "sizeof MathMetricsInfo: " << sizeof(MathMetricsInfo) << "\n";
98         //lyxerr << "sizeof MathCharInset: " << sizeof(MathCharInset) << "\n";
99         //lyxerr << "sizeof LyXFont: " << sizeof(LyXFont) << "\n";
100 }
101
102
103 // simply scrap this function if you want
104 void InsetFormulaBase::mutateToText()
105 {
106 #if 0
107         // translate to latex
108         ostringstream os;
109         latex(NULL, os, false, false);
110         string str = os.str();
111
112         // insert this text
113         LyXText * lt = view_->getLyXText();
114         string::const_iterator cit = str.begin();
115         string::const_iterator end = str.end();
116         for (; cit != end; ++cit)
117                 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
118
119         // remove ourselves
120         //view_->owner()->dispatch(LFUN_ESCAPE);
121 #endif
122 }
123
124
125 void InsetFormulaBase::handleFont
126         (BufferView * bv, string const & arg, string const & font)
127 {
128         bv->lockedInsetStoreUndo(Undo::EDIT);
129         bool sel = mathcursor->selection();
130         if (sel)
131                 updateLocal(bv, true);
132         mathcursor->handleNest(createMathInset(font));
133         mathcursor->insert(arg);
134         if (!sel)
135                 updateLocal(bv, false);
136 }
137
138
139 // Check if uses AMS macros
140 void InsetFormulaBase::validate(LaTeXFeatures &) const
141 {}
142
143
144 void InsetFormulaBase::metrics(BufferView * bv, LyXFont const & f) const
145 {
146         font_ = f;
147         metrics(bv);
148 }
149
150
151 void InsetFormulaBase::metrics(BufferView * bv) const
152 {
153         if (bv)
154                 view_ = bv->owner()->view();
155         MathMetricsInfo mi;
156         mi.base.style = LM_ST_TEXT;
157         mi.base.font  = font_;
158         mi.base.font.setColor(LColor::math);
159         par()->metrics(mi);
160 }
161
162
163 string const InsetFormulaBase::editMessage() const
164 {
165         return _("Math editor mode");
166 }
167
168
169 void InsetFormulaBase::edit(BufferView * bv, int x, int y, mouse_button::state)
170 {
171         if (!bv->lockInset(this))
172                 lyxerr[Debug::MATHED] << "Cannot lock inset!!!" << endl;
173         releaseMathCursor(bv);
174         mathcursor = new MathCursor(this, true);
175         metrics(bv);
176         mathcursor->setPos(x + xo_, y + yo_);
177         // if that is removed, we won't get the magenta box when entering an
178         // inset for the first time
179         bv->updateInset(this, false);
180 }
181
182
183 void InsetFormulaBase::edit(BufferView * bv, bool front)
184 {
185         if (!bv->lockInset(this))
186                 lyxerr << "Cannot lock math inset in edit call!\n";
187         releaseMathCursor(bv);
188         mathcursor = new MathCursor(this, front);
189         metrics(bv);
190         bv->updateInset(this, false);
191 }
192
193
194 void InsetFormulaBase::insetUnlock(BufferView * bv)
195 {
196         if (mathcursor) {
197                 if (mathcursor->inMacroMode()) {
198                         mathcursor->macroModeClose();
199                         updateLocal(bv, true);
200                 }
201                 releaseMathCursor(bv);
202         }
203         generatePreview();
204         bv->updateInset(this, false);
205 }
206
207
208 void InsetFormulaBase::getCursorPos(BufferView *, int & x, int & y) const
209 {
210         // calling metrics here destroys the cached xo,yo positions e.g. in
211         // MathParboxinset. And it would be too expensive anyway...
212         //metrics(bv);
213         if (!mathcursor) {
214                 lyxerr << "getCursorPos - should not happen";
215                 x = y = 0;
216                 return;
217         }
218         mathcursor->getPos(x, y);
219         x -= xo_;
220         y -= yo_;
221         //lyxerr << "getCursorPos: " << x << " " << y << "\n";
222 }
223
224
225 void InsetFormulaBase::toggleInsetCursor(BufferView * bv)
226 {
227         //lyxerr << "toggleInsetCursor: " << isCursorVisible() << "\n";
228         if (isCursorVisible())
229                 hideInsetCursor(bv);
230         else
231                 showInsetCursor(bv);
232 }
233
234
235 void InsetFormulaBase::showInsetCursor(BufferView * bv, bool)
236 {
237         if (isCursorVisible())
238                 return;
239         fitInsetCursor(bv);
240         int x, y, asc, des;
241         getCursorPos(bv, x, y);
242         math_font_max_dim(font_, asc, des);
243         bv->showLockedInsetCursor(x + xo_, y, asc, des);
244         setCursorVisible(true);
245         //lyxerr << "showInsetCursor: " << x << " " << y << "\n";
246 }
247
248
249 void InsetFormulaBase::hideInsetCursor(BufferView * bv)
250 {
251         if (!isCursorVisible())
252                 return;
253         bv->hideLockedInsetCursor();
254         setCursorVisible(false);
255         //lyxerr << "hideInsetCursor: \n";
256 }
257
258
259 void InsetFormulaBase::fitInsetCursor(BufferView * bv) const
260 {
261         if (!mathcursor)
262                 return;
263         int x, y, asc, des;
264         math_font_max_dim(font_, asc, des);
265         getCursorPos(bv, x, y);
266         //y += yo_;
267         //lyxerr << "fitInsetCursor: x: " << x << " y: " << y << " yo: " << yo_ << "\n";
268         bv->fitLockedInsetCursor(x, y, asc, des);
269 }
270
271
272 void InsetFormulaBase::toggleInsetSelection(BufferView * bv)
273 {
274         if (mathcursor)
275                 bv->updateInset(this, false);
276 }
277
278
279 vector<string> const InsetFormulaBase::getLabelList() const
280 {
281   return vector<string>();
282 }
283
284
285 void InsetFormulaBase::updateLocal(BufferView * bv, bool dirty)
286 {
287         bv->updateInset(this, dirty);
288 }
289
290
291 Inset::RESULT InsetFormulaBase::lfunMouseRelease(FuncRequest const & cmd)
292 {
293         if (!mathcursor)
294                 return UNDISPATCHED;
295
296         BufferView * bv = cmd.view();
297         hideInsetCursor(bv);
298         showInsetCursor(bv);
299         bv->updateInset(this, false);
300
301         if (cmd.button() == mouse_button::button3) {
302                 // try to dispatch to enclosed insets first
303                 if (mathcursor->dispatch(cmd) == MathInset::UNDISPATCHED) {     
304                         // launch math panel for right mouse button
305                         bv->owner()->getDialogs().showMathPanel();
306                 }
307                 return DISPATCHED;
308         }
309
310         if (cmd.button() == mouse_button::button1) {
311                 // try to dispatch to enclosed insets first
312                 mathcursor->dispatch(cmd);
313                 // try to set the cursor
314                 //delete mathcursor;
315                 //mathcursor = new MathCursor(this, x == 0);
316                 //metrics(bv);
317                 //mathcursor->setPos(x + xo_, y + yo_);
318                 return DISPATCHED;
319         }
320         return UNDISPATCHED;
321 }
322
323
324 Inset::RESULT InsetFormulaBase::lfunMousePress(FuncRequest const & cmd)
325 {
326         BufferView * bv = cmd.view();
327         releaseMathCursor(bv);
328         mathcursor = new MathCursor(this, cmd.x == 0);
329
330         if (cmd.button() == mouse_button::button1) {
331                 // just set the cursor here
332                 //lyxerr << "setting cursor\n";
333                 metrics(bv);
334                 first_x = cmd.x;
335                 first_y = cmd.y;
336                 mathcursor->selClear();
337                 mathcursor->setPos(cmd.x + xo_, cmd.y + yo_);
338                 mathcursor->dispatch(cmd);
339                 return DISPATCHED;
340         }
341         if (cmd.button() == mouse_button::button3) {
342                 mathcursor->dispatch(cmd);
343                 //delete mathcursor;
344                 return DISPATCHED;
345         }
346         bv->updateInset(this, false);
347         return DISPATCHED;
348 }
349
350
351 Inset::RESULT InsetFormulaBase::lfunMouseMotion(FuncRequest const & cmd)
352 {
353         if (!mathcursor)
354                 return DISPATCHED;
355
356         if (mathcursor->dispatch(FuncRequest(cmd)) != MathInset::UNDISPATCHED)
357                 return DISPATCHED;
358
359         if (abs(cmd.x - first_x) < 2 && abs(cmd.y - first_y) < 2) {
360                 //lyxerr << "insetMotionNotify: ignored\n";
361                 return DISPATCHED;
362         }
363         first_x = cmd.x;
364         first_y = cmd.y;
365
366         if (!mathcursor->selection())
367                 mathcursor->selStart();
368
369         BufferView * bv = cmd.view();
370         hideInsetCursor(bv);
371         mathcursor->setPos(cmd.x + xo_, cmd.y + yo_);
372         showInsetCursor(bv);
373         bv->updateInset(this, false);
374         return DISPATCHED;
375 }
376
377
378 Inset::RESULT InsetFormulaBase::localDispatch(FuncRequest const & cmd)
379 {
380         //lyxerr << "InsetFormulaBase::localDispatch: act: " << cmd.action
381         //      << " arg: '" << cmd.argument
382         //      << " x: '" << cmd.x
383         //      << " y: '" << cmd.y
384         //      << "' button: " << cmd.button() << "\n";
385
386         switch (cmd.action) {
387                 case LFUN_MOUSE_PRESS:
388                         return lfunMousePress(cmd);
389                 case LFUN_MOUSE_MOTION:
390                         return lfunMouseMotion(cmd);
391                 case LFUN_MOUSE_RELEASE:
392                         return lfunMouseRelease(cmd);
393                 default:
394                         break;
395         }
396
397         if (!mathcursor)
398                 return UNDISPATCHED;
399
400         BufferView * bv    = cmd.view();
401         string argument    = cmd.argument;
402         RESULT result      = DISPATCHED;
403         bool sel           = false;
404         bool was_macro     = mathcursor->inMacroMode();
405         bool was_selection = mathcursor->selection();
406
407         hideInsetCursor(bv);
408
409         mathcursor->normalize();
410         mathcursor->touch();
411
412         switch (cmd.action) {
413
414         case LFUN_MATH_MUTATE:
415         case LFUN_MATH_DISPLAY:
416         case LFUN_MATH_NUMBER:
417         case LFUN_MATH_NONUMBER:
418         case LFUN_TABINSERT:
419         case LFUN_BREAKLINE:
420         case LFUN_DELETE_LINE_FORWARD:
421         case LFUN_INSERT_LABEL:
422         case LFUN_MATH_EXTERN:
423         case LFUN_TABULAR_FEATURE:
424         case LFUN_PASTESELECTION:
425                 bv->lockedInsetStoreUndo(Undo::EDIT);
426                 mathcursor->dispatch(cmd);
427                 updateLocal(bv, true);
428                 break;
429
430         case LFUN_WORDRIGHTSEL:
431         case LFUN_RIGHTSEL:
432                 sel = true; // fall through...
433         case LFUN_RIGHT:
434                 result = mathcursor->right(sel) ? DISPATCHED : FINISHED_RIGHT;
435                 //lyxerr << "calling scroll 20\n";
436                 //scroll(bv, 20);
437                 updateLocal(bv, false);
438                 // write something to the minibuffer
439                 //bv->owner()->message(mathcursor->info());
440                 break;
441
442         case LFUN_WORDLEFTSEL:
443         case LFUN_LEFTSEL:
444                 sel = true; // fall through
445         case LFUN_LEFT:
446                 result = mathcursor->left(sel) ? DISPATCHED : FINISHED;
447                 updateLocal(bv, false);
448                 break;
449
450         case LFUN_UPSEL:
451                 sel = true; // fall through
452         case LFUN_UP:
453                 result = mathcursor->up(sel) ? DISPATCHED : FINISHED_UP;
454                 updateLocal(bv, false);
455                 break;
456
457         case LFUN_DOWNSEL:
458                 sel = true; // fall through
459         case LFUN_DOWN:
460                 result = mathcursor->down(sel) ? DISPATCHED : FINISHED_DOWN;
461                 updateLocal(bv, false);
462                 break;
463
464         case LFUN_HOMESEL:
465                 sel = true; // fall through
466         case LFUN_HOME:
467                 result = mathcursor->home(sel) ? DISPATCHED : FINISHED;
468                 updateLocal(bv, false);
469                 break;
470
471         case LFUN_ENDSEL:
472                 sel = true; // fall through
473         case LFUN_END:
474                 result = mathcursor->end(sel) ? DISPATCHED : FINISHED_RIGHT;
475                 updateLocal(bv, false);
476                 break;
477
478         case LFUN_PRIORSEL:
479         case LFUN_PRIOR:
480                 result = FINISHED_UP;
481                 updateLocal(bv, false);
482                 break;
483
484         case LFUN_NEXTSEL:
485         case LFUN_NEXT:
486                 result = FINISHED_DOWN;
487                 updateLocal(bv, false);
488                 break;
489
490         case LFUN_TAB:
491                 mathcursor->idxNext();
492                 updateLocal(bv, false);
493                 break;
494
495         case LFUN_SHIFT_TAB:
496                 mathcursor->idxPrev();
497                 updateLocal(bv, false);
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(cmd.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 (cmd.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, cmd.argument, "lyxgreek"); break;
578         case LFUN_BOLD:         handleFont(bv, cmd.argument, "textbf"); break;
579         case LFUN_SANS:         handleFont(bv, cmd.argument, "textsf"); break;
580         case LFUN_EMPH:         handleFont(bv, cmd.argument, "mathcal"); break;
581         case LFUN_ROMAN:        handleFont(bv, cmd.argument, "mathrm"); break;
582         case LFUN_CODE:         handleFont(bv, cmd.argument, "texttt"); break;
583         case LFUN_FRAK:         handleFont(bv, cmd.argument, "mathfrak"); break;
584         case LFUN_ITAL:         handleFont(bv, cmd.argument, "mathit"); break;
585         case LFUN_NOUN:         handleFont(bv, cmd.argument, "mathbb"); break;
586         case LFUN_DEFAULT:      handleFont(bv, cmd.argument, "textnormal"); break;
587         case LFUN_FREE:         handleFont(bv, cmd.argument, "textrm"); break;
588
589         case LFUN_GREEK:
590                 handleFont(bv, cmd.argument, "lyxgreek1");
591                 if (cmd.argument.size())
592                         mathcursor->interpret(cmd.argument);
593                 break;
594
595         case LFUN_MATH_MODE:
596                 if (mathcursor->currentMode())
597                         handleFont(bv, cmd.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 (!cmd.argument.empty()) {
623                         bv->lockedInsetStoreUndo(Undo::EDIT);
624                         mathcursor->interpret("matrix " + cmd.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(cmd.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(cmd.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_EXEC_COMMAND:
668                 result = UNDISPATCHED;
669                 break;
670
671         case LFUN_INSET_ERT:
672                 // interpret this as if a backslash was typed
673                 bv->lockedInsetStoreUndo(Undo::EDIT);
674                 mathcursor->interpret('\\');
675                 updateLocal(bv, true);
676                 break;
677
678         case LFUN_BREAKPARAGRAPH:
679         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
680         case LFUN_BREAKPARAGRAPH_SKIP:
681                 argument = "\n";
682                 // fall through
683
684         case -1:
685         case LFUN_INSERT_MATH:
686         case LFUN_SELFINSERT:
687                 if (!argument.empty()) {
688                         bv->lockedInsetStoreUndo(Undo::EDIT);
689                         if (argument.size() == 1)
690                                 result = mathcursor->interpret(argument[0]) ? DISPATCHED : FINISHED_RIGHT;
691                         else
692                                 result = mathcursor->interpret(argument) ? DISPATCHED : FINISHED_RIGHT;
693                         updateLocal(bv, true);
694                 }
695                 break;
696
697         case LFUN_MATH_PANEL:
698                 result = UNDISPATCHED;
699                 break;
700
701         case LFUN_ESCAPE:
702                 if (mathcursor->selection())
703                         mathcursor->selClear();
704                 else
705                         result = UNDISPATCHED;
706                 break;
707
708         case LFUN_INSET_TOGGLE:
709                 mathcursor->insetToggle();
710                 updateLocal(bv, true);
711                 break;
712
713         case LFUN_REF_INSERT:
714                 //if (argument.empty()) {
715                 //      InsetCommandParams p("ref");
716                 //      owner_->getDialogs().createRef(p.getAsString());
717                 //} else {
718                 //      InsetCommandParams p;
719                 //      p.setFromString(argument);
720
721                 //      InsetRef * inset = new InsetRef(p, *buffer_);
722                 //      if (!insertInset(inset))
723                 //              delete inset;
724                 //      else
725                 //              updateInset(inset, true);
726                 //}
727                 //
728                 if (cmd.argument.empty()) {
729                         InsetCommandParams p("ref");
730                         bv->owner()->getDialogs().createRef(p.getAsString());
731                 } else {
732                         //mathcursor->handleNest(new InsetRef2);
733                         //mathcursor->insert(arg);
734                         mathcursor->insert(MathAtom(new RefInset(cmd.argument)));
735                 }
736                 updateLocal(bv, true);
737                 break;
738
739         default:
740                 result = UNDISPATCHED;
741         }
742
743         mathcursor->normalize();
744         mathcursor->touch();
745
746         lyx::Assert(mathcursor);
747
748         if (mathcursor->selection() || was_selection)
749                 toggleInsetSelection(bv);
750
751         if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
752             result == UNDISPATCHED) {
753                 fitInsetCursor(bv);
754                 showInsetCursor(bv);
755                 revealCodes(bv);
756         } else {
757                 releaseMathCursor(bv);
758                 bv->unlockInset(this);
759         }
760
761         return result;  // original version
762 }
763
764
765 void InsetFormulaBase::revealCodes(BufferView * bv) const
766 {
767         if (!mathcursor)
768                 return;
769         bv->owner()->message(mathcursor->info());
770
771 #if 0
772         // write something to the minibuffer
773         // translate to latex
774         mathcursor->markInsert();
775         ostringstream os;
776         write(NULL, os);
777         string str = os.str();
778         mathcursor->markErase();
779         string::size_type pos = 0;
780         string res;
781         for (string::iterator it = str.begin(); it != str.end(); ++it) {
782                 if (*it == '\n')
783                         res += ' ';
784                 else if (*it == '\0') {
785                         res += "  -X-  ";
786                         pos = it - str.begin();
787                 }
788                 else
789                         res += *it;
790         }
791         if (pos > 30)
792                 res = res.substr(pos - 30);
793         if (res.size() > 60)
794                 res = res.substr(0, 60);
795         bv->owner()->message(res);
796 #endif
797 }
798
799
800 Inset::Code InsetFormulaBase::lyxCode() const
801 {
802         return Inset::MATH_CODE;
803 }
804
805
806 int InsetFormulaBase::ylow() const
807 {
808         return yo_ - ascent(view(), font_);
809 }
810
811
812 int InsetFormulaBase::yhigh() const
813 {
814         return yo_ + descent(view(), font_);
815 }
816
817
818 int InsetFormulaBase::xlow() const
819 {
820         return xo_;
821 }
822
823
824 int InsetFormulaBase::xhigh() const
825 {
826         return xo_ + width(view(), font_);
827 }
828
829
830 /////////////////////////////////////////////////////////////////////
831
832
833 bool InsetFormulaBase::searchForward(BufferView * bv, string const & str,
834                                      bool, bool)
835 {
836 #ifdef WITH_WARNINGS
837 #warning pretty ugly
838 #endif
839         static InsetFormulaBase * lastformula = 0;
840         static MathIterator current = MathIterator(ibegin(par().nucleus()));
841         static MathArray ar;
842         static string laststr;
843
844         if (lastformula != this || laststr != str) {
845                 //lyxerr << "reset lastformula to " << this << "\n";
846                 lastformula = this;
847                 laststr = str;
848                 current = ibegin(par().nucleus());
849                 ar.clear();
850                 mathed_parse_cell(ar, str);
851         } else {
852                 ++current;
853         }
854         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
855
856         for (MathIterator it = current; it != iend(par().nucleus()); ++it) {
857                 if (it.cell().matchpart(ar, it.back().pos_)) {
858                         bv->unlockInset(bv->theLockingInset());
859                         if (!bv->lockInset(this)) {
860                                 lyxerr << "Cannot lock inset" << endl;
861                                 return false;
862                         }
863                         delete mathcursor;
864                         mathcursor = new MathCursor(this, true);
865                         metrics(bv);
866                         mathcursor->setSelection(it, ar.size());
867                         current = it;
868                         it.jump(ar.size());
869                         updateLocal(bv, false);
870                         return true;
871                 }
872         }
873
874         //lyxerr << "not found!\n";
875         lastformula = 0;
876         return false;
877 }
878
879
880 bool InsetFormulaBase::searchBackward(BufferView * bv, string const & what,
881                                       bool a, bool b)
882 {
883         lyxerr[Debug::MATHED] << "searching backward not implemented in mathed\n";
884         return searchForward(bv, what, a, b);
885 }
886
887
888 bool InsetFormulaBase::display() const
889 {
890         return par()->asHullInset() && par()->asHullInset()->display();
891 }
892
893
894 /////////////////////////////////////////////////////////////////////
895
896
897 void mathDispatchCreation(FuncRequest const & cmd, bool display)
898 {
899         BufferView * bv = cmd.view();
900         // use selection if available..
901         //string sel;
902         //if (action == LFUN_MATH_IMPORT_SELECTION)
903         //      sel = "";
904         //else
905
906         string sel = bv->getLyXText()->selectionAsString(bv->buffer(), false);
907
908         if (sel.empty()) {
909                 InsetFormula * f = new InsetFormula(bv);
910                 if (openNewInset(bv, f)) {
911                         bv->theLockingInset()->
912                                 localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
913                         // don't do that also for LFUN_MATH_MODE unless you want end up with
914                         // always changing to mathrm when opening an inlined inset
915                         // -- I really hate "LyXfunc overloading"...
916                         if (display)
917                                 f->localDispatch(FuncRequest(bv, LFUN_MATH_DISPLAY));
918                         f->localDispatch(FuncRequest(bv, LFUN_INSERT_MATH, cmd.argument));
919                 }
920         } else {
921                 // create a macro if we see "\\newcommand" somewhere, and an ordinary
922                 // formula otherwise
923                 InsetFormulaBase * f;
924                 if (sel.find("\\newcommand") == string::npos &&
925                                 sel.find("\\def") == string::npos)
926                         f = new InsetFormula(sel);
927                 else
928                         f = new InsetFormulaMacro(sel);
929                 bv->getLyXText()->cutSelection(bv);
930                 openNewInset(bv, f);
931         }
932         cmd.message(N_("Math editor mode"));
933 }
934
935
936 void mathDispatch(FuncRequest const & cmd)
937 {
938         BufferView * bv = cmd.view();
939         if (!bv->available())
940                 return;
941
942         switch (cmd.action) {
943
944                 case LFUN_MATH_DISPLAY:
945                         mathDispatchCreation(cmd, true);
946                         break;
947
948                 case LFUN_MATH_MODE:
949                         mathDispatchCreation(cmd, false);
950                         break;
951
952                 case LFUN_MATH_IMPORT_SELECTION:
953                         mathDispatchCreation(cmd, false);
954                         break;
955
956                 case LFUN_MATH_MACRO:
957                         if (cmd.argument.empty())
958                                 cmd.errorMessage(N_("Missing argument"));
959                         else {
960                                 string s = cmd.argument;
961                                 string const s1 = token(s, ' ', 1);
962                                 int const na = s1.empty() ? 0 : lyx::atoi(s1);
963                                 openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
964                         }
965                         break;
966
967                 case LFUN_GREEK: 
968                 case LFUN_INSERT_MATH: 
969                 case LFUN_INSERT_MATRIX: 
970                 case LFUN_MATH_DELIM: {
971                         InsetFormula * f = new InsetFormula(bv);
972                         if (openNewInset(bv, f)) {
973                                 bv->theLockingInset()-> 
974                                         localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
975                                 bv->theLockingInset()->localDispatch(cmd);
976                         }
977                         break;
978                 }
979                 default:
980                         break;
981         }
982 }