]> git.lyx.org Git - features.git/blob - src/mathed/formulabase.C
Fix mouse selection
[features.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 "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 MetricsInfo: " << sizeof(MetricsInfo) << "\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         MetricsInfo 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                         //lyxerr << "Mouse motion\n";
422                         return lfunMouseMotion(cmd);
423                 case LFUN_MOUSE_RELEASE:
424                         //lyxerr << "Mouse single release\n";
425                         return lfunMouseRelease(cmd);
426                 case LFUN_MOUSE_DOUBLE:
427                         //lyxerr << "Mouse double\n";
428                         return localDispatch(FuncRequest(LFUN_WORDSEL));
429                 default:
430                         break;
431         }
432
433         if (!mathcursor)
434                 return UNDISPATCHED;
435
436         BufferView * bv    = cmd.view();
437         string argument    = cmd.argument;
438         RESULT result      = DISPATCHED;
439         bool sel           = false;
440         bool was_macro     = mathcursor->inMacroMode();
441         bool was_selection = mathcursor->selection();
442
443         hideInsetCursor(bv);
444
445         mathcursor->normalize();
446         mathcursor->touch();
447
448         switch (cmd.action) {
449
450         case LFUN_MATH_MUTATE:
451         case LFUN_MATH_DISPLAY:
452         case LFUN_MATH_NUMBER:
453         case LFUN_MATH_NONUMBER:
454         case LFUN_CELL_SPLIT:
455         case LFUN_BREAKLINE:
456         case LFUN_DELETE_LINE_FORWARD:
457         case LFUN_INSERT_LABEL:
458         case LFUN_MATH_EXTERN:
459         case LFUN_TABULAR_FEATURE:
460         case LFUN_PASTESELECTION:
461         case LFUN_MATH_LIMITS:
462                 bv->lockedInsetStoreUndo(Undo::EDIT);
463                 mathcursor->dispatch(cmd);
464                 break;
465
466         case LFUN_RIGHTSEL:
467                 sel = true; // fall through...
468         case LFUN_RIGHT:
469                 result = mathcursor->right(sel) ? DISPATCHED : FINISHED_RIGHT;
470                 //lyxerr << "calling scroll 20\n";
471                 //scroll(bv, 20);
472                 // write something to the minibuffer
473                 //bv->owner()->message(mathcursor->info());
474                 break;
475
476         case LFUN_LEFTSEL:
477                 sel = true; // fall through
478         case LFUN_LEFT:
479                 result = mathcursor->left(sel) ? DISPATCHED : FINISHED;
480                 break;
481
482         case LFUN_UPSEL:
483                 sel = true; // fall through
484         case LFUN_UP:
485                 result = mathcursor->up(sel) ? DISPATCHED : FINISHED_UP;
486                 break;
487
488         case LFUN_DOWNSEL:
489                 sel = true; // fall through
490         case LFUN_DOWN:
491                 result = mathcursor->down(sel) ? DISPATCHED : FINISHED_DOWN;
492                 break;
493
494         case LFUN_WORDSEL:
495                 mathcursor->home(false);
496                 mathcursor->end(true);
497                 break;
498
499         case LFUN_UP_PARAGRAPHSEL:
500         case LFUN_UP_PARAGRAPH:
501         case LFUN_DOWN_PARAGRAPHSEL:
502         case LFUN_DOWN_PARAGRAPH:
503                 result = FINISHED;
504                 break;
505
506         case LFUN_HOMESEL:
507         case LFUN_WORDLEFTSEL:
508                 sel = true; // fall through
509         case LFUN_HOME:
510         case LFUN_WORDLEFT:
511                 result = mathcursor->home(sel) ? DISPATCHED : FINISHED;
512                 break;
513
514         case LFUN_ENDSEL:
515         case LFUN_WORDRIGHTSEL:
516                 sel = true; // fall through
517         case LFUN_END:
518         case LFUN_WORDRIGHT:
519                 result = mathcursor->end(sel) ? DISPATCHED : FINISHED_RIGHT;
520                 break;
521
522         case LFUN_PRIORSEL:
523         case LFUN_PRIOR:
524         case LFUN_BEGINNINGBUFSEL:
525         case LFUN_BEGINNINGBUF:
526                 result = FINISHED;
527                 break;
528
529         case LFUN_NEXTSEL:
530         case LFUN_NEXT:
531         case LFUN_ENDBUFSEL:
532         case LFUN_ENDBUF:
533                 result = FINISHED_RIGHT;
534                 break;
535
536         case LFUN_CELL_FORWARD:
537                 mathcursor->idxNext();
538                 break;
539
540         case LFUN_CELL_BACKWARD:
541                 mathcursor->idxPrev();
542                 break;
543
544         case LFUN_DELETE_WORD_BACKWARD:
545         case LFUN_BACKSPACE:
546                 bv->lockedInsetStoreUndo(Undo::EDIT);
547                 if (!mathcursor->backspace()) {
548                         result = FINISHED;
549                         remove_inset = true;
550                 }
551                 break;
552
553         case LFUN_DELETE_WORD_FORWARD:
554         case LFUN_DELETE:
555                 bv->lockedInsetStoreUndo(Undo::EDIT);
556                 if (!mathcursor->erase()) {
557                         result = FINISHED;
558                         remove_inset = true;
559                 }
560                 break;
561
562         //    case LFUN_GETXY:
563         //      sprintf(dispatch_buffer, "%d %d",);
564         //      dispatch_result = dispatch_buffer;
565         //      break;
566         case LFUN_SETXY: {
567                 lyxerr << "LFUN_SETXY broken!\n";
568                 int x = 0;
569                 int y = 0;
570                 istringstream is(cmd.argument.c_str());
571                 is >> x >> y;
572                 mathcursor->setPos(x, y);
573                 break;
574         }
575
576         case LFUN_PASTE:
577                 if (was_macro)
578                         mathcursor->macroModeClose();
579                 bv->lockedInsetStoreUndo(Undo::EDIT);
580                 mathcursor->selPaste();
581                 break;
582
583         case LFUN_CUT:
584                 bv->lockedInsetStoreUndo(Undo::DELETE);
585                 mathcursor->selCut();
586                 break;
587
588         case LFUN_COPY:
589                 mathcursor->selCopy();
590                 break;
591
592
593         // Special casing for superscript in case of LyX handling
594         // dead-keys:
595         case LFUN_CIRCUMFLEX:
596                 if (cmd.argument.empty()) {
597                         // do superscript if LyX handles
598                         // deadkeys
599                         bv->lockedInsetStoreUndo(Undo::EDIT);
600                         mathcursor->script(true);
601                 }
602                 break;
603
604         case LFUN_UMLAUT:
605         case LFUN_ACUTE:
606         case LFUN_GRAVE:
607         case LFUN_BREVE:
608         case LFUN_DOT:
609         case LFUN_MACRON:
610         case LFUN_CARON:
611         case LFUN_TILDE:
612         case LFUN_CEDILLA:
613         case LFUN_CIRCLE:
614         case LFUN_UNDERDOT:
615         case LFUN_TIE:
616         case LFUN_OGONEK:
617         case LFUN_HUNG_UMLAUT:
618                 break;
619
620         //  Math fonts
621         case LFUN_BOLD:         handleFont(bv, cmd.argument, "mathbf"); break;
622         case LFUN_SANS:         handleFont(bv, cmd.argument, "mathsf"); break;
623         case LFUN_EMPH:         handleFont(bv, cmd.argument, "mathcal"); break;
624         case LFUN_ROMAN:        handleFont(bv, cmd.argument, "mathrm"); break;
625         case LFUN_CODE:         handleFont(bv, cmd.argument, "texttt"); break;
626         case LFUN_FRAK:         handleFont(bv, cmd.argument, "mathfrak"); break;
627         case LFUN_ITAL:         handleFont(bv, cmd.argument, "mathit"); break;
628         case LFUN_NOUN:         handleFont(bv, cmd.argument, "mathbb"); break;
629         case LFUN_FREEFONT_APPLY:  handleFont(bv, cmd.argument, "textrm"); break;
630         case LFUN_DEFAULT:      handleFont(bv, cmd.argument, "textnormal"); break;
631
632         case LFUN_MATH_MODE:
633                 if (mathcursor->currentMode() == MathInset::TEXT_MODE)
634                         mathcursor->niceInsert(MathAtom(new MathHullInset("simple")));
635                 else
636                         handleFont(bv, cmd.argument, "textrm");
637                 //bv->owner()->message(_("math text mode toggled"));
638                 break;
639
640         case LFUN_MATH_SIZE:
641 #if 0
642                 if (!arg.empty()) {
643                         bv->lockedInsetStoreUndo(Undo::EDIT);
644                         mathcursor->setSize(arg);
645                 }
646 #endif
647                 break;
648
649         case LFUN_INSERT_MATRIX: {
650                 bv->lockedInsetStoreUndo(Undo::EDIT);
651                 unsigned int m = 1;
652                 unsigned int n = 1;
653                 string v_align;
654                 string h_align;
655                 istringstream is(STRCONV(argument));
656                 is >> m >> n >> v_align >> h_align;
657                 m = max(1u, m);
658                 n = max(1u, n);
659                 v_align += 'c';
660                 mathcursor->niceInsert(
661                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
662                 break;
663         }
664
665         case LFUN_SUPERSCRIPT:
666         case LFUN_SUBSCRIPT:
667         {
668                 bv->lockedInsetStoreUndo(Undo::EDIT);
669                 mathcursor->script(cmd.action == LFUN_SUPERSCRIPT);
670                 break;
671         }
672
673         case LFUN_MATH_DELIM:
674         {
675                 //lyxerr << "formulabase::LFUN_MATH_DELIM, arg: '" << arg << "'\n";
676                 string ls;
677                 string rs = split(cmd.argument, ls, ' ');
678                 // Reasonable default values
679                 if (ls.empty())
680                         ls = '(';
681                 if (rs.empty())
682                         rs = ')';
683
684                 bv->lockedInsetStoreUndo(Undo::EDIT);
685                 mathcursor->handleNest(MathAtom(new MathDelimInset(ls, rs)));
686                 break;
687         }
688
689         case LFUN_PROTECTEDSPACE:
690         case LFUN_MATH_SPACE:
691                 bv->lockedInsetStoreUndo(Undo::EDIT);
692                 mathcursor->insert(MathAtom(new MathSpaceInset(",")));
693                 break;
694
695         case LFUN_UNDO:
696                 bv->owner()->message(_("Invalid action in math mode!"));
697                 break;
698
699
700         case LFUN_EXEC_COMMAND:
701                 result = UNDISPATCHED;
702                 break;
703
704         case LFUN_INSET_ERT:
705                 // interpret this as if a backslash was typed
706                 bv->lockedInsetStoreUndo(Undo::EDIT);
707                 mathcursor->interpret('\\');
708                 break;
709
710         case LFUN_BREAKPARAGRAPH:
711         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
712         case LFUN_BREAKPARAGRAPH_SKIP:
713                 argument = "\n";
714                 // fall through
715
716 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
717 // handling such that "self-insert" works on "arbitrary stuff" too, and
718 // math-insert only handles special math things like "matrix".
719         case LFUN_INSERT_MATH:
720                 bv->lockedInsetStoreUndo(Undo::EDIT);
721                 mathcursor->niceInsert(argument);
722                 break;
723
724         case -1:
725         case LFUN_SELFINSERT:
726                 if (!argument.empty()) {
727                         bv->lockedInsetStoreUndo(Undo::EDIT);
728                         if (argument.size() == 1)
729                                 result = mathcursor->interpret(argument[0]) ? DISPATCHED : FINISHED_RIGHT;
730                         else
731                                 mathcursor->insert(asArray(argument));
732                 }
733                 break;
734
735         case LFUN_MATH_PANEL:
736                 result = UNDISPATCHED;
737                 break;
738
739         case LFUN_ESCAPE:
740                 if (mathcursor->selection())
741                         mathcursor->selClear();
742                 else
743                         result = UNDISPATCHED;
744                 break;
745
746         case LFUN_INSET_TOGGLE:
747                 mathcursor->insetToggle();
748                 break;
749
750         case LFUN_DIALOG_SHOW_NEW_INSET: {
751                 string const & name = argument;
752                 string data;
753                 if (name == "ref") {
754                         RefInset tmp(name);
755                         data = tmp.createDialogStr(name);
756                 }
757
758                 if (data.empty())
759                         result = UNDISPATCHED;
760                 else {
761                         bv->owner()->getDialogs().show(name, data, 0);
762                 }
763         }
764         break;
765
766         case LFUN_INSET_APPLY: {
767                 string const name = cmd.getArg(0);
768                 InsetBase * base =
769                         bv->owner()->getDialogs().getOpenInset(name);
770
771                 if (base) {
772                         FuncRequest fr(bv, LFUN_INSET_MODIFY, cmd.argument);
773                         result = base->localDispatch(fr);
774                 } else {
775                         MathArray ar;
776                         if (createMathInset_fromDialogStr(cmd.argument, ar)) {
777                                 mathcursor->insert(ar);
778                                 result = DISPATCHED;
779                         } else {
780                                 result = UNDISPATCHED;
781                         }
782                 }
783         }
784         break;
785
786         default:
787                 result = UNDISPATCHED;
788         }
789
790         if (result == DISPATCHED)
791                 bv->updateInset(this);
792
793         mathcursor->normalize();
794         mathcursor->touch();
795
796         lyx::Assert(mathcursor);
797
798         if (mathcursor->selection() || was_selection)
799                 toggleInsetSelection(bv);
800
801         if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
802             result == UNDISPATCHED) {
803                 fitInsetCursor(bv);
804                 showInsetCursor(bv);
805                 revealCodes(bv);
806                 cmd.view()->stuffClipboard(mathcursor->grabSelection());
807         } else {
808                 releaseMathCursor(bv);
809                 bv->unlockInset(this);
810                 if (remove_inset)
811                         bv->owner()->dispatch(FuncRequest(LFUN_DELETE));
812         }
813
814         return result;  // original version
815 }
816
817
818 void InsetFormulaBase::revealCodes(BufferView * bv) const
819 {
820         if (!mathcursor)
821                 return;
822         bv->owner()->message(mathcursor->info());
823
824 #if 0
825         // write something to the minibuffer
826         // translate to latex
827         mathcursor->markInsert();
828         ostringstream os;
829         write(NULL, os);
830         string str = os.str();
831         mathcursor->markErase();
832         string::size_type pos = 0;
833         string res;
834         for (string::iterator it = str.begin(); it != str.end(); ++it) {
835                 if (*it == '\n')
836                         res += ' ';
837                 else if (*it == '\0') {
838                         res += "  -X-  ";
839                         pos = it - str.begin();
840                 }
841                 else
842                         res += *it;
843         }
844         if (pos > 30)
845                 res = res.substr(pos - 30);
846         if (res.size() > 60)
847                 res = res.substr(0, 60);
848         bv->owner()->message(res);
849 #endif
850 }
851
852
853 Inset::Code InsetFormulaBase::lyxCode() const
854 {
855         return Inset::MATH_CODE;
856 }
857
858
859 int InsetFormulaBase::ylow() const
860 {
861         return yo_ - ascent(view(), font_);
862 }
863
864
865 int InsetFormulaBase::yhigh() const
866 {
867         return yo_ + descent(view(), font_);
868 }
869
870
871 int InsetFormulaBase::xlow() const
872 {
873         return xo_;
874 }
875
876
877 int InsetFormulaBase::xhigh() const
878 {
879         return xo_ + width(view(), font_);
880 }
881
882
883 /////////////////////////////////////////////////////////////////////
884
885
886 bool InsetFormulaBase::searchForward(BufferView * bv, string const & str,
887                                      bool, bool)
888 {
889 #ifdef WITH_WARNINGS
890 #warning pretty ugly
891 #endif
892         static InsetFormulaBase * lastformula = 0;
893         static MathIterator current = MathIterator(ibegin(par().nucleus()));
894         static MathArray ar;
895         static string laststr;
896
897         if (lastformula != this || laststr != str) {
898                 //lyxerr << "reset lastformula to " << this << "\n";
899                 lastformula = this;
900                 laststr = str;
901                 current = ibegin(par().nucleus());
902                 ar.clear();
903                 mathed_parse_cell(ar, str);
904         } else {
905                 ++current;
906         }
907         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
908
909         for (MathIterator it = current; it != iend(par().nucleus()); ++it) {
910                 if (it.cell().matchpart(ar, it.back().pos_)) {
911                         bv->unlockInset(bv->theLockingInset());
912                         if (!bv->lockInset(this)) {
913                                 lyxerr << "Cannot lock inset" << endl;
914                                 return false;
915                         }
916                         delete mathcursor;
917                         mathcursor = new MathCursor(this, true);
918                         metrics(bv);
919                         mathcursor->setSelection(it, ar.size());
920                         current = it;
921                         it.jump(ar.size());
922                         bv->updateInset(this);
923                         return true;
924                 }
925         }
926
927         //lyxerr << "not found!\n";
928         lastformula = 0;
929         return false;
930 }
931
932
933 bool InsetFormulaBase::searchBackward(BufferView * bv, string const & what,
934                                       bool a, bool b)
935 {
936         lyxerr[Debug::MATHED] << "searching backward not implemented in mathed\n";
937         return searchForward(bv, what, a, b);
938 }
939
940
941 bool InsetFormulaBase::display() const
942 {
943         return par()->asHullInset() && par()->asHullInset()->display();
944 }
945
946
947 string InsetFormulaBase::selectionAsString() const
948 {
949         return mathcursor ? mathcursor->grabSelection() : string();
950 }
951
952 /////////////////////////////////////////////////////////////////////
953
954
955 void mathDispatchCreation(FuncRequest const & cmd, bool display)
956 {
957         BufferView * bv = cmd.view();
958         // use selection if available..
959         //string sel;
960         //if (action == LFUN_MATH_IMPORT_SELECTION)
961         //      sel = "";
962         //else
963
964         string sel = bv->getLyXText()->selectionAsString(bv->buffer(), false);
965
966         if (sel.empty()) {
967                 InsetFormula * f = new InsetFormula(bv);
968                 if (openNewInset(bv, f)) {
969                         bv->theLockingInset()->
970                                 localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
971                         // don't do that also for LFUN_MATH_MODE unless you want end up with
972                         // always changing to mathrm when opening an inlined inset
973                         // -- I really hate "LyXfunc overloading"...
974                         if (display)
975                                 f->localDispatch(FuncRequest(bv, LFUN_MATH_DISPLAY));
976                         f->localDispatch(FuncRequest(bv, LFUN_INSERT_MATH, cmd.argument));
977                 }
978         } else {
979                 // create a macro if we see "\\newcommand" somewhere, and an ordinary
980                 // formula otherwise
981                 InsetFormulaBase * f;
982                 if (sel.find("\\newcommand") == string::npos &&
983                                 sel.find("\\def") == string::npos)
984                         f = new InsetFormula(sel);
985                 else
986                         f = new InsetFormulaMacro(sel);
987                 bv->getLyXText()->cutSelection(bv);
988                 openNewInset(bv, f);
989         }
990         cmd.message(N_("Math editor mode"));
991 }
992
993
994 void mathDispatch(FuncRequest const & cmd)
995 {
996         BufferView * bv = cmd.view();
997         if (!bv->available())
998                 return;
999
1000         switch (cmd.action) {
1001
1002                 case LFUN_MATH_DISPLAY:
1003                         mathDispatchCreation(cmd, true);
1004                         break;
1005
1006                 case LFUN_MATH_MODE:
1007                         mathDispatchCreation(cmd, false);
1008                         break;
1009
1010                 case LFUN_MATH_IMPORT_SELECTION:
1011                         mathDispatchCreation(cmd, false);
1012                         break;
1013
1014                 case LFUN_MATH_MACRO:
1015                         if (cmd.argument.empty())
1016                                 cmd.errorMessage(N_("Missing argument"));
1017                         else {
1018                                 string s = cmd.argument;
1019                                 string const s1 = token(s, ' ', 1);
1020                                 int const na = s1.empty() ? 0 : lyx::atoi(s1);
1021                                 openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
1022                         }
1023                         break;
1024
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 }