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