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