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