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