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