]> git.lyx.org Git - lyx.git/blob - src/mathed/formulabase.C
architectural changes to tex2lyx
[lyx.git] / src / mathed / formulabase.C
1 /*
2 *  File:        formulabase.C
3 *  Purpose:     Implementation of common parts of the LyX  math insets
4 *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
5 *  Created:     January 1996
6 *
7 *  Copyright: 1996-1998 Alejandro Aguilar Sierra
8 *
9 *  Version: 0.4, Lyx project.
10 *
11 *   You are free to use and modify this code under the terms of
12 *   the GNU General Public Licence version 2 or later.
13 */
14
15 #include <config.h>
16
17 #include "Lsstream.h"
18 #include "support/LAssert.h"
19 #include "formula.h"
20 #include "formulamacro.h"
21 #include "lyxrc.h"
22 #include "funcrequest.h"
23 #include "BufferView.h"
24 #include "lyxtext.h"
25 #include "gettext.h"
26 #include "LaTeXFeatures.h"
27 #include "debug.h"
28 #include "math_support.h"
29 #include "metricsinfo.h"
30 #include "math_data.h"
31 #include "support/lstrings.h"
32 #include "support/lyxlib.h"
33 #include "frontends/LyXView.h"
34 #include "frontends/font_metrics.h"
35 #include "frontends/mouse_state.h"
36 #include "math_arrayinset.h"
37 #include "math_charinset.h"
38 #include "math_deliminset.h"
39 #include "math_cursor.h"
40 #include "math_factory.h"
41 #include "math_fontinset.h"
42 #include "math_hullinset.h"
43 #include "math_iterator.h"
44 #include "math_macrotable.h"
45 #include "math_parser.h"
46 #include "math_pos.h"
47 #include "math_spaceinset.h"
48 #include "undo_funcs.h"
49 #include "textpainter.h"
50 #include "frontends/Dialogs.h"
51 #include "intl.h"
52 #include "ref_inset.h"
53
54 #include <fstream>
55
56 using namespace lyx::support;
57
58 using std::endl;
59 using std::ostream;
60 using std::vector;
61 using std::abs;
62 using std::max;
63
64
65 MathCursor * mathcursor = 0;
66
67 namespace {
68
69 // local global
70 int first_x;
71 int first_y;
72
73 bool openNewInset(BufferView * bv, UpdatableInset * new_inset)
74 {
75         if (!bv->insertInset(new_inset)) {
76                 delete new_inset;
77                 return false;
78         }
79         new_inset->localDispatch(FuncRequest(bv, LFUN_INSET_EDIT, "left"));
80         return true;
81 }
82
83
84 } // namespace anon
85
86
87
88 InsetFormulaBase::InsetFormulaBase()
89         : xo_(0), yo_(0)
90 {
91         // This is needed as long the math parser is not re-entrant
92         initMath();
93         //lyxerr << "sizeof MathInset: " << sizeof(MathInset) << endl;
94         //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
95         //lyxerr << "sizeof MathCharInset: " << sizeof(MathCharInset) << endl;
96         //lyxerr << "sizeof LyXFont: " << sizeof(LyXFont) << endl;
97 }
98
99
100 // simply scrap this function if you want
101 void InsetFormulaBase::mutateToText()
102 {
103 #if 0
104         // translate to latex
105         ostringstream os;
106         latex(NULL, os, false, false);
107         string str = os.str();
108
109         // insert this text
110         LyXText * lt = view_->getLyXText();
111         string::const_iterator cit = str.begin();
112         string::const_iterator end = str.end();
113         for (; cit != end; ++cit)
114                 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
115
116         // remove ourselves
117         //view_->owner()->dispatch(LFUN_ESCAPE);
118 #endif
119 }
120
121
122 void InsetFormulaBase::handleFont
123         (BufferView * bv, string const & arg, string const & font)
124 {
125         // this whole function is a hack and won't work for incremental font
126         // changes...
127         recordUndo(bv, Undo::ATOMIC);
128
129         if (mathcursor->inset()->name() == font)
130                 mathcursor->handleFont(font);
131         else {
132                 mathcursor->handleNest(createMathInset(font));
133                 mathcursor->insert(arg);
134         }
135 }
136
137
138 BufferView * InsetFormulaBase::view() const
139 {
140         return view_;
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                         bv->updateInset(this);
160                 }
161                 releaseMathCursor(bv);
162         }
163         generatePreview();
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         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_BOLD:         handleFont(bv, cmd.argument, "mathbf"); break;
557         case LFUN_SANS:         handleFont(bv, cmd.argument, "mathsf"); break;
558         case LFUN_EMPH:         handleFont(bv, cmd.argument, "mathcal"); break;
559         case LFUN_ROMAN:        handleFont(bv, cmd.argument, "mathrm"); break;
560         case LFUN_CODE:         handleFont(bv, cmd.argument, "texttt"); break;
561         case LFUN_FRAK:         handleFont(bv, cmd.argument, "mathfrak"); break;
562         case LFUN_ITAL:         handleFont(bv, cmd.argument, "mathit"); break;
563         case LFUN_NOUN:         handleFont(bv, cmd.argument, "mathbb"); break;
564         case LFUN_FREEFONT_APPLY:  handleFont(bv, cmd.argument, "textrm"); break;
565         case LFUN_DEFAULT:      handleFont(bv, cmd.argument, "textnormal"); break;
566
567         case LFUN_MATH_MODE:
568                 if (mathcursor->currentMode() == MathInset::TEXT_MODE)
569                         mathcursor->niceInsert(MathAtom(new MathHullInset("simple")));
570                 else
571                         handleFont(bv, cmd.argument, "textrm");
572                 //bv->owner()->message(_("math text mode toggled"));
573                 break;
574
575         case LFUN_MATH_SIZE:
576 #if 0
577                 if (!arg.empty()) {
578                         recordUndo(bv, Undo::ATOMIC);
579                         mathcursor->setSize(arg);
580                 }
581 #endif
582                 break;
583
584         case LFUN_INSERT_MATRIX: {
585                 recordUndo(bv, Undo::ATOMIC);
586                 unsigned int m = 1;
587                 unsigned int n = 1;
588                 string v_align;
589                 string h_align;
590                 istringstream is(STRCONV(argument));
591                 is >> m >> n >> v_align >> h_align;
592                 m = max(1u, m);
593                 n = max(1u, n);
594                 v_align += 'c';
595                 mathcursor->niceInsert(
596                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
597                 break;
598         }
599
600         case LFUN_SUPERSCRIPT:
601         case LFUN_SUBSCRIPT:
602         {
603                 recordUndo(bv, Undo::ATOMIC);
604                 mathcursor->script(cmd.action == LFUN_SUPERSCRIPT);
605                 break;
606         }
607
608         case LFUN_MATH_DELIM:
609         {
610                 //lyxerr << "formulabase::LFUN_MATH_DELIM, arg: '" << arg << "'" << endl;
611                 string ls;
612                 string rs = split(cmd.argument, ls, ' ');
613                 // Reasonable default values
614                 if (ls.empty())
615                         ls = '(';
616                 if (rs.empty())
617                         rs = ')';
618
619                 recordUndo(bv, Undo::ATOMIC);
620                 mathcursor->handleNest(MathAtom(new MathDelimInset(ls, rs)));
621                 break;
622         }
623
624         case LFUN_SPACE_INSERT:
625         case LFUN_MATH_SPACE:
626                 recordUndo(bv, Undo::ATOMIC);
627                 mathcursor->insert(MathAtom(new MathSpaceInset(",")));
628                 break;
629
630         case LFUN_UNDO:
631                 bv->owner()->message(_("Invalid action in math mode!"));
632                 break;
633
634
635         case LFUN_EXEC_COMMAND:
636                 result = UNDISPATCHED;
637                 break;
638
639         case LFUN_INSET_ERT:
640                 // interpret this as if a backslash was typed
641                 recordUndo(bv, Undo::ATOMIC);
642                 mathcursor->interpret('\\');
643                 break;
644
645         case LFUN_BREAKPARAGRAPH:
646         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
647         case LFUN_BREAKPARAGRAPH_SKIP:
648                 argument = "\n";
649                 // fall through
650
651 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
652 // handling such that "self-insert" works on "arbitrary stuff" too, and
653 // math-insert only handles special math things like "matrix".
654         case LFUN_INSERT_MATH:
655                 recordUndo(bv, Undo::ATOMIC);
656                 mathcursor->niceInsert(argument);
657                 break;
658
659         case -1:
660         case LFUN_SELFINSERT:
661                 if (!argument.empty()) {
662                         recordUndo(bv, Undo::ATOMIC);
663                         if (argument.size() == 1)
664                                 result = mathcursor->interpret(argument[0]) ? DISPATCHED : FINISHED_RIGHT;
665                         else
666                                 mathcursor->insert(argument);
667                 }
668                 break;
669
670         case LFUN_ESCAPE:
671                 if (mathcursor->selection())
672                         mathcursor->selClear();
673                 else
674                         result = UNDISPATCHED;
675                 break;
676
677         case LFUN_INSET_TOGGLE:
678                 mathcursor->insetToggle();
679                 break;
680
681         case LFUN_DIALOG_SHOW:
682                 result = UNDISPATCHED;
683                 break;
684
685         case LFUN_DIALOG_SHOW_NEW_INSET: {
686                 string const & name = argument;
687                 string data;
688                 if (name == "ref") {
689                         RefInset tmp(name);
690                         data = tmp.createDialogStr(name);
691                 }
692
693                 if (data.empty())
694                         result = UNDISPATCHED;
695                 else {
696                         bv->owner()->getDialogs().show(name, data, 0);
697                 }
698         }
699         break;
700
701         case LFUN_INSET_APPLY: {
702                 string const name = cmd.getArg(0);
703                 InsetBase * base =
704                         bv->owner()->getDialogs().getOpenInset(name);
705
706                 if (base) {
707                         FuncRequest fr(bv, LFUN_INSET_MODIFY, cmd.argument);
708                         result = base->localDispatch(fr);
709                 } else {
710                         MathArray ar;
711                         if (createMathInset_fromDialogStr(cmd.argument, ar)) {
712                                 mathcursor->insert(ar);
713                                 result = DISPATCHED;
714                         } else {
715                                 result = UNDISPATCHED;
716                         }
717                 }
718         }
719         break;
720
721         default:
722                 result = UNDISPATCHED;
723         }
724
725         if (result == DISPATCHED)
726                 bv->updateInset(this);
727
728         mathcursor->normalize();
729         mathcursor->touch();
730
731         Assert(mathcursor);
732
733         if (mathcursor->selection() || was_selection)
734                 toggleInsetSelection(bv);
735
736         if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
737             result == UNDISPATCHED) {
738                 fitInsetCursor(bv);
739                 revealCodes(bv);
740                 cmd.view()->stuffClipboard(mathcursor->grabSelection());
741         } else {
742                 releaseMathCursor(bv);
743                 bv->unlockInset(this);
744                 if (remove_inset)
745                         bv->owner()->dispatch(FuncRequest(LFUN_DELETE));
746         }
747
748         return result;  // original version
749 }
750
751
752 void InsetFormulaBase::revealCodes(BufferView * bv) const
753 {
754         if (!mathcursor)
755                 return;
756         bv->owner()->message(mathcursor->info());
757
758 #if 0
759         // write something to the minibuffer
760         // translate to latex
761         mathcursor->markInsert();
762         ostringstream os;
763         write(NULL, os);
764         string str = os.str();
765         mathcursor->markErase();
766         string::size_type pos = 0;
767         string res;
768         for (string::iterator it = str.begin(); it != str.end(); ++it) {
769                 if (*it == '\n')
770                         res += ' ';
771                 else if (*it == '\0') {
772                         res += "  -X-  ";
773                         pos = it - str.begin();
774                 }
775                 else
776                         res += *it;
777         }
778         if (pos > 30)
779                 res = res.substr(pos - 30);
780         if (res.size() > 60)
781                 res = res.substr(0, 60);
782         bv->owner()->message(res);
783 #endif
784 }
785
786
787 InsetOld::Code InsetFormulaBase::lyxCode() const
788 {
789         return InsetOld::MATH_CODE;
790 }
791
792
793 int InsetFormulaBase::ylow() const
794 {
795         return yo_ - dim_.asc;
796 }
797
798
799 int InsetFormulaBase::yhigh() const
800 {
801         return yo_ + dim_.des;
802 }
803
804
805 int InsetFormulaBase::xlow() const
806 {
807         return xo_;
808 }
809
810
811 int InsetFormulaBase::xhigh() const
812 {
813         return xo_ + dim_.wid;
814 }
815
816
817 /////////////////////////////////////////////////////////////////////
818
819
820 bool InsetFormulaBase::searchForward(BufferView * bv, string const & str,
821                                      bool, bool)
822 {
823 #ifdef WITH_WARNINGS
824 #warning pretty ugly
825 #endif
826         static InsetFormulaBase * lastformula = 0;
827         static MathIterator current = MathIterator(ibegin(par().nucleus()));
828         static MathArray ar;
829         static string laststr;
830
831         if (lastformula != this || laststr != str) {
832                 //lyxerr << "reset lastformula to " << this << endl;
833                 lastformula = this;
834                 laststr = str;
835                 current = ibegin(par().nucleus());
836                 ar.clear();
837                 mathed_parse_cell(ar, str);
838         } else {
839                 ++current;
840         }
841         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
842
843         for (MathIterator it = current; it != iend(par().nucleus()); ++it) {
844                 if (it.cell().matchpart(ar, it.back().pos_)) {
845                         bv->unlockInset(bv->theLockingInset());
846                         if (!bv->lockInset(this)) {
847                                 lyxerr << "Cannot lock inset" << endl;
848                                 return false;
849                         }
850                         delete mathcursor;
851                         mathcursor = new MathCursor(this, true);
852                         //metrics(bv);
853                         mathcursor->setSelection(it, ar.size());
854                         current = it;
855                         it.jump(ar.size());
856                         bv->updateInset(this);
857                         return true;
858                 }
859         }
860
861         //lyxerr << "not found!" << endl;
862         lastformula = 0;
863         return false;
864 }
865
866
867 bool InsetFormulaBase::searchBackward(BufferView * bv, string const & what,
868                                       bool a, bool b)
869 {
870         lyxerr[Debug::MATHED] << "searching backward not implemented in mathed" << endl;
871         return searchForward(bv, what, a, b);
872 }
873
874
875 bool InsetFormulaBase::display() const
876 {
877         return par()->asHullInset() && par()->asHullInset()->display();
878 }
879
880
881 string InsetFormulaBase::selectionAsString() const
882 {
883         return mathcursor ? mathcursor->grabSelection() : string();
884 }
885
886 /////////////////////////////////////////////////////////////////////
887
888
889 void mathDispatchCreation(FuncRequest const & cmd, bool display)
890 {
891         BufferView * bv = cmd.view();
892         // use selection if available..
893         //string sel;
894         //if (action == LFUN_MATH_IMPORT_SELECTION)
895         //      sel = "";
896         //else
897
898         string sel = bv->getLyXText()->selectionAsString(bv->buffer(), false);
899
900         if (sel.empty()) {
901                 InsetFormula * f = new InsetFormula(bv);
902                 if (openNewInset(bv, f)) {
903                         bv->theLockingInset()->
904                                 localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
905                         // don't do that also for LFUN_MATH_MODE unless you want end up with
906                         // always changing to mathrm when opening an inlined inset
907                         // -- I really hate "LyXfunc overloading"...
908                         if (display)
909                                 f->localDispatch(FuncRequest(bv, LFUN_MATH_DISPLAY));
910                         f->localDispatch(FuncRequest(bv, LFUN_INSERT_MATH, cmd.argument));
911                 }
912         } else {
913                 // create a macro if we see "\\newcommand" somewhere, and an ordinary
914                 // formula otherwise
915                 InsetFormulaBase * f;
916                 if (sel.find("\\newcommand") == string::npos &&
917                                 sel.find("\\def") == string::npos)
918                         f = new InsetFormula(sel);
919                 else
920                         f = new InsetFormulaMacro(sel);
921                 bv->getLyXText()->cutSelection(true, false);
922                 openNewInset(bv, f);
923         }
924         cmd.message(N_("Math editor mode"));
925 }
926
927
928 void mathDispatch(FuncRequest const & cmd)
929 {
930         BufferView * bv = cmd.view();
931         if (!bv->available())
932                 return;
933
934         switch (cmd.action) {
935
936                 case LFUN_MATH_DISPLAY:
937                         mathDispatchCreation(cmd, true);
938                         break;
939
940                 case LFUN_MATH_MODE:
941                         mathDispatchCreation(cmd, false);
942                         break;
943
944                 case LFUN_MATH_IMPORT_SELECTION:
945                         mathDispatchCreation(cmd, false);
946                         break;
947
948                 case LFUN_MATH_MACRO:
949                         if (cmd.argument.empty())
950                                 cmd.errorMessage(N_("Missing argument"));
951                         else {
952                                 string s = cmd.argument;
953                                 string const s1 = token(s, ' ', 1);
954                                 int const nargs = s1.empty() ? 0 : atoi(s1);
955                                 string const s2 = token(s, ' ', 2);
956                                 string const type = s2.empty() ? "newcommand" : s2;
957                                 openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), nargs, s2));
958                         }
959                         break;
960
961                 case LFUN_INSERT_MATH:
962                 case LFUN_INSERT_MATRIX:
963                 case LFUN_MATH_DELIM: {
964                         InsetFormula * f = new InsetFormula(bv);
965                         if (openNewInset(bv, f)) {
966                                 bv->theLockingInset()->
967                                         localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
968                                 bv->theLockingInset()->localDispatch(cmd);
969                         }
970                         break;
971                 }
972
973                 default:
974                         break;
975         }
976 }