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