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