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