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