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