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