]> git.lyx.org Git - lyx.git/blob - src/mathed/formulabase.C
*** empty log message ***
[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 = "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_REF_APPLY: {
808                 // argument comes with a head "LatexCommand " and a
809                 // tail "\nend_inset\n\n". Strip them off.
810                 string trimmed;
811                 string body = split(argument, trimmed, ' ');
812                 split(body, trimmed, '\n');
813                 lyxerr << "passing '" << trimmed << "' to the math parser\n";
814
815                 MathArray ar;
816                 mathed_parse_cell(ar, trimmed);
817                 if (ar.size() != 1) {
818                         result = UNDISPATCHED;
819                         break;
820                 }
821
822                 RefInset * tmp = ar[0].nucleus()->asRefInset();
823                 if (!tmp) {
824                         result = UNDISPATCHED;
825                         break;
826                 }
827
828                 InsetBase * base =
829                         bv->owner()->getDialogs().getOpenInset("ref");
830                 if (base) {
831                         RefInset * inset = dynamic_cast<RefInset *>(base);
832                         if (!inset) {
833                                 result = UNDISPATCHED;
834                                 break;
835                         }
836
837                         *inset = *tmp;
838                 } else {
839                         mathcursor->insert(ar);
840                 }
841                 updateLocal(bv, true);
842         }
843         break;
844
845         default:
846                 result = UNDISPATCHED;
847         }
848
849         mathcursor->normalize();
850         mathcursor->touch();
851
852         lyx::Assert(mathcursor);
853
854         if (mathcursor->selection() || was_selection)
855                 toggleInsetSelection(bv);
856
857         if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
858             result == UNDISPATCHED) {
859                 fitInsetCursor(bv);
860                 showInsetCursor(bv);
861                 revealCodes(bv);
862                 cmd.view()->stuffClipboard(mathcursor->grabSelection());
863         } else {
864                 releaseMathCursor(bv);
865                 bv->unlockInset(this);
866                 if (remove_inset)
867                         bv->owner()->dispatch(FuncRequest(LFUN_DELETE));
868         }
869
870         return result;  // original version
871 }
872
873
874 void InsetFormulaBase::revealCodes(BufferView * bv) const
875 {
876         if (!mathcursor)
877                 return;
878         bv->owner()->message(mathcursor->info());
879
880 #if 0
881         // write something to the minibuffer
882         // translate to latex
883         mathcursor->markInsert();
884         ostringstream os;
885         write(NULL, os);
886         string str = os.str();
887         mathcursor->markErase();
888         string::size_type pos = 0;
889         string res;
890         for (string::iterator it = str.begin(); it != str.end(); ++it) {
891                 if (*it == '\n')
892                         res += ' ';
893                 else if (*it == '\0') {
894                         res += "  -X-  ";
895                         pos = it - str.begin();
896                 }
897                 else
898                         res += *it;
899         }
900         if (pos > 30)
901                 res = res.substr(pos - 30);
902         if (res.size() > 60)
903                 res = res.substr(0, 60);
904         bv->owner()->message(res);
905 #endif
906 }
907
908
909 Inset::Code InsetFormulaBase::lyxCode() const
910 {
911         return Inset::MATH_CODE;
912 }
913
914
915 int InsetFormulaBase::ylow() const
916 {
917         return yo_ - ascent(view(), font_);
918 }
919
920
921 int InsetFormulaBase::yhigh() const
922 {
923         return yo_ + descent(view(), font_);
924 }
925
926
927 int InsetFormulaBase::xlow() const
928 {
929         return xo_;
930 }
931
932
933 int InsetFormulaBase::xhigh() const
934 {
935         return xo_ + width(view(), font_);
936 }
937
938
939 /////////////////////////////////////////////////////////////////////
940
941
942 bool InsetFormulaBase::searchForward(BufferView * bv, string const & str,
943                                      bool, bool)
944 {
945 #ifdef WITH_WARNINGS
946 #warning pretty ugly
947 #endif
948         static InsetFormulaBase * lastformula = 0;
949         static MathIterator current = MathIterator(ibegin(par().nucleus()));
950         static MathArray ar;
951         static string laststr;
952
953         if (lastformula != this || laststr != str) {
954                 //lyxerr << "reset lastformula to " << this << "\n";
955                 lastformula = this;
956                 laststr = str;
957                 current = ibegin(par().nucleus());
958                 ar.clear();
959                 mathed_parse_cell(ar, str);
960         } else {
961                 ++current;
962         }
963         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
964
965         for (MathIterator it = current; it != iend(par().nucleus()); ++it) {
966                 if (it.cell().matchpart(ar, it.back().pos_)) {
967                         bv->unlockInset(bv->theLockingInset());
968                         if (!bv->lockInset(this)) {
969                                 lyxerr << "Cannot lock inset" << endl;
970                                 return false;
971                         }
972                         delete mathcursor;
973                         mathcursor = new MathCursor(this, true);
974                         metrics(bv);
975                         mathcursor->setSelection(it, ar.size());
976                         current = it;
977                         it.jump(ar.size());
978                         updateLocal(bv, false);
979                         return true;
980                 }
981         }
982
983         //lyxerr << "not found!\n";
984         lastformula = 0;
985         return false;
986 }
987
988
989 bool InsetFormulaBase::searchBackward(BufferView * bv, string const & what,
990                                       bool a, bool b)
991 {
992         lyxerr[Debug::MATHED] << "searching backward not implemented in mathed\n";
993         return searchForward(bv, what, a, b);
994 }
995
996
997 bool InsetFormulaBase::display() const
998 {
999         return par()->asHullInset() && par()->asHullInset()->display();
1000 }
1001
1002
1003 string InsetFormulaBase::selectionAsString() const
1004 {
1005         return mathcursor ? mathcursor->grabSelection() : string();
1006 }
1007
1008 /////////////////////////////////////////////////////////////////////
1009
1010
1011 void mathDispatchCreation(FuncRequest const & cmd, bool display)
1012 {
1013         BufferView * bv = cmd.view();
1014         // use selection if available..
1015         //string sel;
1016         //if (action == LFUN_MATH_IMPORT_SELECTION)
1017         //      sel = "";
1018         //else
1019
1020         string sel = bv->getLyXText()->selectionAsString(bv->buffer(), false);
1021
1022         if (sel.empty()) {
1023                 InsetFormula * f = new InsetFormula(bv);
1024                 if (openNewInset(bv, f)) {
1025                         bv->theLockingInset()->
1026                                 localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
1027                         // don't do that also for LFUN_MATH_MODE unless you want end up with
1028                         // always changing to mathrm when opening an inlined inset
1029                         // -- I really hate "LyXfunc overloading"...
1030                         if (display)
1031                                 f->localDispatch(FuncRequest(bv, LFUN_MATH_DISPLAY));
1032                         f->localDispatch(FuncRequest(bv, LFUN_INSERT_MATH, cmd.argument));
1033                 }
1034         } else {
1035                 // create a macro if we see "\\newcommand" somewhere, and an ordinary
1036                 // formula otherwise
1037                 InsetFormulaBase * f;
1038                 if (sel.find("\\newcommand") == string::npos &&
1039                                 sel.find("\\def") == string::npos)
1040                         f = new InsetFormula(sel);
1041                 else
1042                         f = new InsetFormulaMacro(sel);
1043                 bv->getLyXText()->cutSelection(bv);
1044                 openNewInset(bv, f);
1045         }
1046         cmd.message(N_("Math editor mode"));
1047 }
1048
1049
1050 void mathDispatch(FuncRequest const & cmd)
1051 {
1052         BufferView * bv = cmd.view();
1053         if (!bv->available())
1054                 return;
1055
1056         switch (cmd.action) {
1057
1058                 case LFUN_MATH_DISPLAY:
1059                         mathDispatchCreation(cmd, true);
1060                         break;
1061
1062                 case LFUN_MATH_MODE:
1063                         mathDispatchCreation(cmd, false);
1064                         break;
1065
1066                 case LFUN_MATH_IMPORT_SELECTION:
1067                         mathDispatchCreation(cmd, false);
1068                         break;
1069
1070                 case LFUN_MATH_MACRO:
1071                         if (cmd.argument.empty())
1072                                 cmd.errorMessage(N_("Missing argument"));
1073                         else {
1074                                 string s = cmd.argument;
1075                                 string const s1 = token(s, ' ', 1);
1076                                 int const na = s1.empty() ? 0 : lyx::atoi(s1);
1077                                 openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
1078                         }
1079                         break;
1080
1081                 case LFUN_GREEK:
1082                 case LFUN_INSERT_MATH:
1083                 case LFUN_INSERT_MATRIX:
1084                 case LFUN_MATH_DELIM: {
1085                         InsetFormula * f = new InsetFormula(bv);
1086                         if (openNewInset(bv, f)) {
1087                                 bv->theLockingInset()->
1088                                         localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
1089                                 bv->theLockingInset()->localDispatch(cmd);
1090                         }
1091                         break;
1092                 }
1093                 default:
1094                         break;
1095         }
1096 }