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