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