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