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