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