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