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