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