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