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