]> git.lyx.org Git - features.git/blob - src/mathed/formulabase.C
Undo cleaned up. It seems to work pretty well now.
[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         recordUndo(bv, Undo::ATOMIC);
128
129         if (mathcursor->inset()->name() == font)
130                 mathcursor->handleFont(font);
131         else {
132                 mathcursor->handleNest(createMathInset(font));
133                 mathcursor->insert(arg);
134         }
135 }
136
137
138 BufferView * InsetFormulaBase::view() const
139 {
140         return view_;
141 }
142
143
144 void InsetFormulaBase::validate(LaTeXFeatures &) const
145 {}
146
147
148 string const InsetFormulaBase::editMessage() const
149 {
150         return _("Math editor mode");
151 }
152
153
154 void InsetFormulaBase::insetUnlock(BufferView * bv)
155 {
156         if (mathcursor) {
157                 if (mathcursor->inMacroMode()) {
158                         mathcursor->macroModeClose();
159                         bv->updateInset(this);
160                 }
161                 releaseMathCursor(bv);
162         }
163         generatePreview();
164         bv->updateInset(this);
165 }
166
167
168 void InsetFormulaBase::getCursor(BufferView &, int & x, int & y) const
169 {
170         mathcursor->getPos(x, y);
171 }
172
173
174 void InsetFormulaBase::getCursorPos(BufferView *, int & x, int & y) const
175 {
176         // calling metrics here destroys the cached xo,yo positions e.g. in
177         // MathParboxinset. And it would be too expensive anyway...
178         //metrics(bv);
179         if (!mathcursor) {
180                 lyxerr << "getCursorPos - should not happen";
181                 x = y = 0;
182                 return;
183         }
184         mathcursor->getPos(x, y);
185         x = mathcursor->targetX();
186         x -= xo_;
187         y -= yo_;
188         //lyxerr << "getCursorPos: " << x << ' ' << y << endl;
189 }
190
191
192 void InsetFormulaBase::fitInsetCursor(BufferView * bv) const
193 {
194         if (!mathcursor)
195                 return;
196         int x, y, asc, des;
197         asc = 10;
198         des = 2;
199         //math_font_max_dim(font_, asc, des);
200         getCursorPos(bv, x, y);
201         //y += yo_;
202         //lyxerr << "fitInsetCursor: x: " << x << " y: " << y << " yo: " << yo_ << endl;
203         bv->fitLockedInsetCursor(x, y, asc, des);
204 }
205
206
207 void InsetFormulaBase::toggleInsetSelection(BufferView * bv)
208 {
209         if (mathcursor)
210                 bv->updateInset(this);
211 }
212
213
214 vector<string> const InsetFormulaBase::getLabelList() const
215 {
216   return vector<string>();
217 }
218
219
220 dispatch_result InsetFormulaBase::lfunMouseRelease(FuncRequest const & cmd)
221 {
222         if (!mathcursor)
223                 return UNDISPATCHED;
224
225         BufferView * bv = cmd.view();
226         bv->updateInset(this);
227         //lyxerr << "lfunMouseRelease: buttons: " << cmd.button() << endl;
228
229         if (cmd.button() == mouse_button::button3) {
230                 // try to dispatch to enclosed insets first
231                 if (mathcursor->dispatch(cmd) == UNDISPATCHED) {
232                         // launch math panel for right mouse button
233                         lyxerr << "lfunMouseRelease: undispatched: " << cmd.button() << endl;
234                         bv->owner()->getDialogs().show("mathpanel");
235                 }
236                 return DISPATCHED;
237         }
238
239         if (cmd.button() == mouse_button::button2) {
240                 MathArray ar;
241                 asArray(bv->getClipboard(), ar);
242                 mathcursor->selClear();
243                 mathcursor->setPos(cmd.x + xo_, cmd.y + yo_);
244                 mathcursor->insert(ar);
245                 bv->updateInset(this);
246                 return DISPATCHED;
247         }
248
249         if (cmd.button() == mouse_button::button1) {
250                 // try to dispatch to enclosed insets first
251                 mathcursor->dispatch(cmd);
252                 cmd.view()->stuffClipboard(mathcursor->grabSelection());
253                 // try to set the cursor
254                 //delete mathcursor;
255                 //mathcursor = new MathCursor(this, x == 0);
256                 //metrics(bv);
257                 //mathcursor->setPos(x + xo_, y + yo_);
258                 return DISPATCHED;
259         }
260
261         return UNDISPATCHED;
262 }
263
264
265 dispatch_result InsetFormulaBase::lfunMousePress(FuncRequest const & cmd)
266 {
267         BufferView * bv = cmd.view();
268         //lyxerr << "lfunMousePress: buttons: " << cmd.button() << endl;
269
270         if (!mathcursor || mathcursor->formula() != this) {
271                 lyxerr[Debug::MATHED] << "re-create cursor" << endl;
272                 releaseMathCursor(bv);
273                 mathcursor = new MathCursor(this, cmd.x == 0);
274                 //metrics(bv);
275                 mathcursor->setPos(cmd.x + xo_, cmd.y + yo_);
276         }
277
278         if (cmd.button() == mouse_button::button3) {
279                 mathcursor->dispatch(cmd);
280                 return DISPATCHED;
281         }
282
283         if (cmd.button() == mouse_button::button1) {
284                 first_x = cmd.x;
285                 first_y = cmd.y;
286                 mathcursor->selClear();
287                 mathcursor->setPos(cmd.x + xo_, cmd.y + yo_);
288                 mathcursor->dispatch(cmd);
289                 return DISPATCHED;
290         }
291
292         bv->updateInset(this);
293         return DISPATCHED;
294 }
295
296
297 dispatch_result InsetFormulaBase::lfunMouseMotion(FuncRequest const & cmd)
298 {
299         if (!mathcursor)
300                 return DISPATCHED;
301
302         if (mathcursor->dispatch(FuncRequest(cmd)) != UNDISPATCHED)
303                 return DISPATCHED;
304
305         // only select with button 1
306         if (cmd.button() != mouse_button::button1)
307                 return DISPATCHED;
308
309         if (abs(cmd.x - first_x) < 2 && abs(cmd.y - first_y) < 2)
310                 return DISPATCHED;
311
312         first_x = cmd.x;
313         first_y = cmd.y;
314
315         if (!mathcursor->selection())
316                 mathcursor->selStart();
317
318         BufferView * bv = cmd.view();
319         mathcursor->setPos(cmd.x + xo_, cmd.y + yo_);
320         bv->updateInset(this);
321         return DISPATCHED;
322 }
323
324
325 dispatch_result InsetFormulaBase::localDispatch(FuncRequest const & cmd)
326 {
327         //lyxerr << "InsetFormulaBase::localDispatch: act: " << cmd.action
328         //      << " arg: '" << cmd.argument
329         //      << " x: '" << cmd.x
330         //      << " y: '" << cmd.y
331         //      << "' button: " << cmd.button() << endl;
332
333         BufferView * bv = cmd.view();
334
335         // delete empty mathbox (LFUN_BACKSPACE and LFUN_DELETE)
336         bool remove_inset = false;
337
338         switch (cmd.action) {
339                 case LFUN_INSET_EDIT:
340                         lyxerr << "Called EDIT with '" << cmd.argument << "'\n";
341                         if (!bv->lockInset(this))
342                                 lyxerr << "Cannot lock math inset in edit call!\n";
343                         releaseMathCursor(bv);
344                         if (!cmd.argument.empty()) {
345                                 mathcursor = new MathCursor(this, cmd.argument == "left");
346                                 //metrics(bv);
347                         } else {
348                                 mathcursor = new MathCursor(this, true);
349                                 //metrics(bv);
350                                 mathcursor->setPos(cmd.x + xo_, cmd.y + yo_);
351                         }
352                         // if that is removed, we won't get the magenta box when entering an
353                         // inset for the first time
354                         bv->updateInset(this);
355                         return DISPATCHED;
356
357                 case LFUN_MOUSE_PRESS:
358                         //lyxerr << "Mouse single press\n";
359                         return lfunMousePress(cmd);
360                 case LFUN_MOUSE_MOTION:
361                         //lyxerr << "Mouse motion\n";
362                         return lfunMouseMotion(cmd);
363                 case LFUN_MOUSE_RELEASE:
364                         //lyxerr << "Mouse single release\n";
365                         return lfunMouseRelease(cmd);
366                 case LFUN_MOUSE_DOUBLE:
367                         //lyxerr << "Mouse double\n";
368                         return localDispatch(FuncRequest(LFUN_WORDSEL));
369                 default:
370                         break;
371         }
372
373         if (!mathcursor)
374                 return UNDISPATCHED;
375
376         string argument    = cmd.argument;
377         RESULT result      = DISPATCHED;
378         bool sel           = false;
379         bool was_macro     = mathcursor->inMacroMode();
380         bool was_selection = mathcursor->selection();
381
382         mathcursor->normalize();
383         mathcursor->touch();
384
385         switch (cmd.action) {
386
387         case LFUN_MATH_MUTATE:
388         case LFUN_MATH_DISPLAY:
389         case LFUN_MATH_NUMBER:
390         case LFUN_MATH_NONUMBER:
391         case LFUN_CELL_SPLIT:
392         case LFUN_BREAKLINE:
393         case LFUN_DELETE_LINE_FORWARD:
394         case LFUN_INSERT_LABEL:
395         case LFUN_MATH_EXTERN:
396         case LFUN_TABULAR_FEATURE:
397         case LFUN_PASTESELECTION:
398         case LFUN_MATH_LIMITS:
399                 recordUndo(bv, Undo::ATOMIC);
400                 mathcursor->dispatch(cmd);
401                 break;
402
403         case LFUN_RIGHTSEL:
404                 sel = true; // fall through...
405         case LFUN_RIGHT:
406                 result = mathcursor->right(sel) ? DISPATCHED : FINISHED_RIGHT;
407                 //lyxerr << "calling scroll 20\n";
408                 //scroll(bv, 20);
409                 // write something to the minibuffer
410                 //bv->owner()->message(mathcursor->info());
411                 break;
412
413         case LFUN_LEFTSEL:
414                 sel = true; // fall through
415         case LFUN_LEFT:
416                 result = mathcursor->left(sel) ? DISPATCHED : FINISHED;
417                 break;
418
419         case LFUN_UPSEL:
420                 sel = true; // fall through
421         case LFUN_UP:
422                 result = mathcursor->up(sel) ? DISPATCHED : FINISHED_UP;
423                 break;
424
425         case LFUN_DOWNSEL:
426                 sel = true; // fall through
427         case LFUN_DOWN:
428                 result = mathcursor->down(sel) ? DISPATCHED : FINISHED_DOWN;
429                 break;
430
431         case LFUN_WORDSEL:
432                 mathcursor->home(false);
433                 mathcursor->end(true);
434                 break;
435
436         case LFUN_UP_PARAGRAPHSEL:
437         case LFUN_UP_PARAGRAPH:
438         case LFUN_DOWN_PARAGRAPHSEL:
439         case LFUN_DOWN_PARAGRAPH:
440                 result = FINISHED;
441                 break;
442
443         case LFUN_HOMESEL:
444         case LFUN_WORDLEFTSEL:
445                 sel = true; // fall through
446         case LFUN_HOME:
447         case LFUN_WORDLEFT:
448                 result = mathcursor->home(sel) ? DISPATCHED : FINISHED;
449                 break;
450
451         case LFUN_ENDSEL:
452         case LFUN_WORDRIGHTSEL:
453                 sel = true; // fall through
454         case LFUN_END:
455         case LFUN_WORDRIGHT:
456                 result = mathcursor->end(sel) ? DISPATCHED : FINISHED_RIGHT;
457                 break;
458
459         case LFUN_PRIORSEL:
460         case LFUN_PRIOR:
461         case LFUN_BEGINNINGBUFSEL:
462         case LFUN_BEGINNINGBUF:
463                 result = FINISHED;
464                 break;
465
466         case LFUN_NEXTSEL:
467         case LFUN_NEXT:
468         case LFUN_ENDBUFSEL:
469         case LFUN_ENDBUF:
470                 result = FINISHED_RIGHT;
471                 break;
472
473         case LFUN_CELL_FORWARD:
474                 mathcursor->idxNext();
475                 break;
476
477         case LFUN_CELL_BACKWARD:
478                 mathcursor->idxPrev();
479                 break;
480
481         case LFUN_DELETE_WORD_BACKWARD:
482         case LFUN_BACKSPACE:
483                 recordUndo(bv, Undo::ATOMIC);
484                 if (!mathcursor->backspace()) {
485                         result = FINISHED;
486                         remove_inset = true;
487                 }
488                 break;
489
490         case LFUN_DELETE_WORD_FORWARD:
491         case LFUN_DELETE:
492                 recordUndo(bv, Undo::ATOMIC);
493                 if (!mathcursor->erase()) {
494                         result = FINISHED;
495                         remove_inset = true;
496                 }
497                 break;
498
499         //    case LFUN_GETXY:
500         //      sprintf(dispatch_buffer, "%d %d",);
501         //      dispatch_result = dispatch_buffer;
502         //      break;
503         case LFUN_SETXY: {
504                 lyxerr << "LFUN_SETXY broken!\n";
505                 int x = 0;
506                 int y = 0;
507                 istringstream is(cmd.argument.c_str());
508                 is >> x >> y;
509                 mathcursor->setPos(x, y);
510                 break;
511         }
512
513         case LFUN_PASTE: {
514                 size_t n = 0;
515                 istringstream is(cmd.argument.c_str());
516                 is >> n;
517                 if (was_macro)
518                         mathcursor->macroModeClose();
519                 recordUndo(bv, Undo::ATOMIC);
520                 mathcursor->selPaste(n);
521                 break;
522         }
523
524         case LFUN_CUT:
525                 recordUndo(bv, Undo::DELETE);
526                 mathcursor->selCut();
527                 break;
528
529         case LFUN_COPY:
530                 mathcursor->selCopy();
531                 break;
532
533
534         // Special casing for superscript in case of LyX handling
535         // dead-keys:
536         case LFUN_CIRCUMFLEX:
537                 if (cmd.argument.empty()) {
538                         // do superscript if LyX handles
539                         // deadkeys
540                         recordUndo(bv, Undo::ATOMIC);
541                         mathcursor->script(true);
542                 }
543                 break;
544
545         case LFUN_UMLAUT:
546         case LFUN_ACUTE:
547         case LFUN_GRAVE:
548         case LFUN_BREVE:
549         case LFUN_DOT:
550         case LFUN_MACRON:
551         case LFUN_CARON:
552         case LFUN_TILDE:
553         case LFUN_CEDILLA:
554         case LFUN_CIRCLE:
555         case LFUN_UNDERDOT:
556         case LFUN_TIE:
557         case LFUN_OGONEK:
558         case LFUN_HUNG_UMLAUT:
559                 break;
560
561         //  Math fonts
562         case LFUN_BOLD:         handleFont(bv, cmd.argument, "mathbf"); break;
563         case LFUN_SANS:         handleFont(bv, cmd.argument, "mathsf"); break;
564         case LFUN_EMPH:         handleFont(bv, cmd.argument, "mathcal"); break;
565         case LFUN_ROMAN:        handleFont(bv, cmd.argument, "mathrm"); break;
566         case LFUN_CODE:         handleFont(bv, cmd.argument, "texttt"); break;
567         case LFUN_FRAK:         handleFont(bv, cmd.argument, "mathfrak"); break;
568         case LFUN_ITAL:         handleFont(bv, cmd.argument, "mathit"); break;
569         case LFUN_NOUN:         handleFont(bv, cmd.argument, "mathbb"); break;
570         case LFUN_FREEFONT_APPLY:  handleFont(bv, cmd.argument, "textrm"); break;
571         case LFUN_DEFAULT:      handleFont(bv, cmd.argument, "textnormal"); break;
572
573         case LFUN_MATH_MODE:
574                 if (mathcursor->currentMode() == MathInset::TEXT_MODE)
575                         mathcursor->niceInsert(MathAtom(new MathHullInset("simple")));
576                 else
577                         handleFont(bv, cmd.argument, "textrm");
578                 //bv->owner()->message(_("math text mode toggled"));
579                 break;
580
581         case LFUN_MATH_SIZE:
582 #if 0
583                 if (!arg.empty()) {
584                         recordUndo(bv, Undo::ATOMIC);
585                         mathcursor->setSize(arg);
586                 }
587 #endif
588                 break;
589
590         case LFUN_INSERT_MATRIX: {
591                 recordUndo(bv, Undo::ATOMIC);
592                 unsigned int m = 1;
593                 unsigned int n = 1;
594                 string v_align;
595                 string h_align;
596                 istringstream is(STRCONV(argument));
597                 is >> m >> n >> v_align >> h_align;
598                 m = max(1u, m);
599                 n = max(1u, n);
600                 v_align += 'c';
601                 mathcursor->niceInsert(
602                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
603                 break;
604         }
605
606         case LFUN_SUPERSCRIPT:
607         case LFUN_SUBSCRIPT:
608         {
609                 recordUndo(bv, Undo::ATOMIC);
610                 mathcursor->script(cmd.action == LFUN_SUPERSCRIPT);
611                 break;
612         }
613
614         case LFUN_MATH_DELIM:
615         {
616                 //lyxerr << "formulabase::LFUN_MATH_DELIM, arg: '" << arg << "'\n";
617                 string ls;
618                 string rs = split(cmd.argument, ls, ' ');
619                 // Reasonable default values
620                 if (ls.empty())
621                         ls = '(';
622                 if (rs.empty())
623                         rs = ')';
624
625                 recordUndo(bv, Undo::ATOMIC);
626                 mathcursor->handleNest(MathAtom(new MathDelimInset(ls, rs)));
627                 break;
628         }
629
630         case LFUN_SPACE_INSERT:
631         case LFUN_MATH_SPACE:
632                 recordUndo(bv, Undo::ATOMIC);
633                 mathcursor->insert(MathAtom(new MathSpaceInset(",")));
634                 break;
635
636         case LFUN_UNDO:
637                 bv->owner()->message(_("Invalid action in math mode!"));
638                 break;
639
640
641         case LFUN_EXEC_COMMAND:
642                 result = UNDISPATCHED;
643                 break;
644
645         case LFUN_INSET_ERT:
646                 // interpret this as if a backslash was typed
647                 recordUndo(bv, Undo::ATOMIC);
648                 mathcursor->interpret('\\');
649                 break;
650
651         case LFUN_BREAKPARAGRAPH:
652         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
653         case LFUN_BREAKPARAGRAPH_SKIP:
654                 argument = "\n";
655                 // fall through
656
657 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
658 // handling such that "self-insert" works on "arbitrary stuff" too, and
659 // math-insert only handles special math things like "matrix".
660         case LFUN_INSERT_MATH:
661                 recordUndo(bv, Undo::ATOMIC);
662                 mathcursor->niceInsert(argument);
663                 break;
664
665         case -1:
666         case LFUN_SELFINSERT:
667                 if (!argument.empty()) {
668                         recordUndo(bv, Undo::ATOMIC);
669                         if (argument.size() == 1)
670                                 result = mathcursor->interpret(argument[0]) ? DISPATCHED : FINISHED_RIGHT;
671                         else
672                                 mathcursor->insert(argument);
673                 }
674                 break;
675
676         case LFUN_ESCAPE:
677                 if (mathcursor->selection())
678                         mathcursor->selClear();
679                 else
680                         result = UNDISPATCHED;
681                 break;
682
683         case LFUN_INSET_TOGGLE:
684                 mathcursor->insetToggle();
685                 break;
686
687         case LFUN_DIALOG_SHOW:
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 }