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