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