]> git.lyx.org Git - lyx.git/blob - src/mathed/formulabase.C
the string -> char patch
[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 << "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 << "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_HOMESEL:
510         case LFUN_WORDLEFTSEL:
511                 sel = true; // fall through
512         case LFUN_HOME:
513         case LFUN_WORDLEFT:
514                 result = mathcursor->home(sel) ? DISPATCHED : FINISHED;
515                 updateLocal(bv, false);
516                 break;
517
518         case LFUN_ENDSEL:
519         case LFUN_WORDRIGHTSEL:
520                 sel = true; // fall through
521         case LFUN_END:
522         case LFUN_WORDRIGHT:
523                 result = mathcursor->end(sel) ? DISPATCHED : FINISHED_RIGHT;
524                 updateLocal(bv, false);
525                 break;
526
527         case LFUN_PRIORSEL:
528         case LFUN_PRIOR:
529         case LFUN_BEGINNINGBUFSEL:
530         case LFUN_BEGINNINGBUF:
531                 result = FINISHED_UP;
532                 updateLocal(bv, false);
533                 break;
534
535         case LFUN_NEXTSEL:
536         case LFUN_NEXT:
537         case LFUN_ENDBUFSEL:
538         case LFUN_ENDBUF:
539                 result = FINISHED_DOWN;
540                 updateLocal(bv, false);
541                 break;
542
543         case LFUN_TAB:
544                 mathcursor->idxNext();
545                 updateLocal(bv, false);
546                 break;
547
548         case LFUN_SHIFT_TAB:
549                 mathcursor->idxPrev();
550                 updateLocal(bv, false);
551                 break;
552
553         case LFUN_DELETE_WORD_BACKWARD:
554         case LFUN_BACKSPACE:
555                 bv->lockedInsetStoreUndo(Undo::DELETE);
556                 mathcursor->backspace();
557                 updateLocal(bv, true);
558                 break;
559
560         case LFUN_DELETE_WORD_FORWARD:
561         case LFUN_DELETE:
562                 bv->lockedInsetStoreUndo(Undo::DELETE);
563                 mathcursor->erase();
564                 bv->updateInset(this, true);
565                 break;
566
567         //    case LFUN_GETXY:
568         //      sprintf(dispatch_buffer, "%d %d",);
569         //      dispatch_result = dispatch_buffer;
570         //      break;
571         case LFUN_SETXY: {
572                 lyxerr << "LFUN_SETXY broken!\n";
573                 int x = 0;
574                 int y = 0;
575                 istringstream is(cmd.argument.c_str());
576                 is >> x >> y;
577                 mathcursor->setPos(x, y);
578                 updateLocal(bv, false);
579                 break;
580         }
581
582         case LFUN_PASTE:
583                 if (was_macro)
584                         mathcursor->macroModeClose();
585                 bv->lockedInsetStoreUndo(Undo::EDIT);
586                 mathcursor->selPaste();
587                 updateLocal(bv, true);
588                 break;
589
590         case LFUN_CUT:
591                 bv->lockedInsetStoreUndo(Undo::DELETE);
592                 mathcursor->selCut();
593                 updateLocal(bv, true);
594                 break;
595
596         case LFUN_COPY:
597                 mathcursor->selCopy();
598                 break;
599
600
601         // Special casing for superscript in case of LyX handling
602         // dead-keys:
603         case LFUN_CIRCUMFLEX:
604                 if (cmd.argument.empty()) {
605                         // do superscript if LyX handles
606                         // deadkeys
607                         bv->lockedInsetStoreUndo(Undo::EDIT);
608                         mathcursor->script(true);
609                         updateLocal(bv, true);
610                 }
611                 break;
612
613         case LFUN_UMLAUT:
614         case LFUN_ACUTE:
615         case LFUN_GRAVE:
616         case LFUN_BREVE:
617         case LFUN_DOT:
618         case LFUN_MACRON:
619         case LFUN_CARON:
620         case LFUN_TILDE:
621         case LFUN_CEDILLA:
622         case LFUN_CIRCLE:
623         case LFUN_UNDERDOT:
624         case LFUN_TIE:
625         case LFUN_OGONEK:
626         case LFUN_HUNG_UMLAUT:
627                 break;
628
629         //  Math fonts
630         case LFUN_GREEK_TOGGLE: handleFont(bv, cmd.argument, "lyxgreek"); break;
631         case LFUN_BOLD:         handleFont(bv, cmd.argument, "mathbf"); break;
632         case LFUN_SANS:         handleFont(bv, cmd.argument, "mathsf"); break;
633         case LFUN_EMPH:         handleFont(bv, cmd.argument, "mathcal"); break;
634         case LFUN_ROMAN:        handleFont(bv, cmd.argument, "mathrm"); break;
635         case LFUN_CODE:         handleFont(bv, cmd.argument, "texttt"); break;
636         case LFUN_FRAK:         handleFont(bv, cmd.argument, "mathfrak"); break;
637         case LFUN_ITAL:         handleFont(bv, cmd.argument, "mathit"); break;
638         case LFUN_NOUN:         handleFont(bv, cmd.argument, "mathbb"); break;
639         case LFUN_FREE:         handleFont(bv, cmd.argument, "textrm"); break;
640         case LFUN_DEFAULT:      handleFont(bv, cmd.argument, "textnormal"); break;
641
642         case LFUN_GREEK:
643                 handleFont(bv, cmd.argument, "lyxgreek1");
644                 if (cmd.argument.size())
645                         mathcursor->insert(asArray(cmd.argument));
646                 break;
647
648         case LFUN_MATH_MODE:
649                 if (mathcursor->currentMode() == MathInset::TEXT_MODE) {
650                         mathcursor->niceInsert(MathAtom(new MathHullInset("simple")));
651                         updateLocal(bv, true);
652                 } else {
653                         handleFont(bv, cmd.argument, "textrm");
654                 }
655                 //bv->owner()->message(_("math text mode toggled"));
656                 break;
657
658         case LFUN_MATH_SIZE:
659 #if 0
660                 if (!arg.empty()) {
661                         bv->lockedInsetStoreUndo(Undo::EDIT);
662                         mathcursor->setSize(arg);
663                         updateLocal(bv, true);
664                 }
665 #endif
666                 break;
667
668         case LFUN_INSERT_MATRIX: {
669                 bv->lockedInsetStoreUndo(Undo::EDIT);
670                 unsigned int m = 1;
671                 unsigned int n = 1;
672                 string v_align;
673                 string h_align;
674                 istringstream is(STRCONV(argument));
675                 is >> m >> n >> v_align >> h_align;
676                 m = max(1u, m);
677                 n = max(1u, n);
678                 v_align += 'c';
679                 mathcursor->niceInsert(
680                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
681                         updateLocal(bv, true);
682                 break;
683         }
684
685         case LFUN_SUPERSCRIPT:
686         case LFUN_SUBSCRIPT:
687         {
688                 bv->lockedInsetStoreUndo(Undo::EDIT);
689                 mathcursor->script(cmd.action == LFUN_SUPERSCRIPT);
690                 updateLocal(bv, true);
691                 break;
692         }
693
694         case LFUN_MATH_DELIM:
695         {
696                 //lyxerr << "formulabase::LFUN_MATH_DELIM, arg: '" << arg << "'\n";
697                 string ls;
698                 string rs = split(cmd.argument, ls, ' ');
699                 // Reasonable default values
700                 if (ls.empty())
701                         ls = '(';
702                 if (rs.empty())
703                         rs = ')';
704
705                 bv->lockedInsetStoreUndo(Undo::EDIT);
706                 mathcursor->handleNest(MathAtom(new MathDelimInset(ls, rs)));
707                 updateLocal(bv, true);
708                 break;
709         }
710
711         case LFUN_PROTECTEDSPACE:
712         case LFUN_MATH_SPACE:
713                 bv->lockedInsetStoreUndo(Undo::EDIT);
714                 mathcursor->insert(MathAtom(new MathSpaceInset(",")));
715                 updateLocal(bv, true);
716                 break;
717
718         case LFUN_UNDO:
719                 bv->owner()->message(_("Invalid action in math mode!"));
720                 break;
721
722
723         case LFUN_EXEC_COMMAND:
724                 result = UNDISPATCHED;
725                 break;
726
727         case LFUN_INSET_ERT:
728                 // interpret this as if a backslash was typed
729                 bv->lockedInsetStoreUndo(Undo::EDIT);
730                 mathcursor->interpret('\\');
731                 updateLocal(bv, true);
732                 break;
733
734         case LFUN_BREAKPARAGRAPH:
735         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
736         case LFUN_BREAKPARAGRAPH_SKIP:
737                 argument = "\n";
738                 // fall through
739
740 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
741 // handling such that "self-insert" works on "arbitrary stuff" too, and
742 // math-insert only handles special math things like "matrix".
743         case LFUN_INSERT_MATH:
744                 bv->lockedInsetStoreUndo(Undo::EDIT);
745                 mathcursor->niceInsert(argument);
746                 updateLocal(bv, true);
747                 break;
748
749         case -1:
750         case LFUN_SELFINSERT:
751                 if (!argument.empty()) {
752                         bv->lockedInsetStoreUndo(Undo::EDIT);
753                         if (argument.size() == 1)
754                                 result = mathcursor->interpret(argument[0]) ? DISPATCHED : FINISHED_RIGHT;
755                         else
756                                 mathcursor->insert(asArray(argument));
757                         updateLocal(bv, true);
758                 }
759                 break;
760
761         case LFUN_MATH_PANEL:
762                 result = UNDISPATCHED;
763                 break;
764
765         case LFUN_ESCAPE:
766                 if (mathcursor->selection())
767                         mathcursor->selClear();
768                 else
769                         result = UNDISPATCHED;
770                 break;
771
772         case LFUN_INSET_TOGGLE:
773                 mathcursor->insetToggle();
774                 updateLocal(bv, true);
775                 break;
776
777         case LFUN_REF_INSERT:
778                 //if (argument.empty()) {
779                 //      InsetCommandParams p("ref");
780                 //      owner_->getDialogs().createRef(p.getAsString());
781                 //} else {
782                 //      InsetCommandParams p;
783                 //      p.setFromString(argument);
784
785                 //      InsetRef * inset = new InsetRef(p, *buffer_);
786                 //      if (!insertInset(inset))
787                 //              delete inset;
788                 //      else
789                 //              updateInset(inset, true);
790                 //}
791                 //
792                 if (cmd.argument.empty()) {
793                         InsetCommandParams p("ref");
794                         bv->owner()->getDialogs().createRef(p.getAsString());
795                 } else {
796                         //mathcursor->handleNest(new InsetRef2);
797                         //mathcursor->insert(arg);
798                         mathcursor->insert(MathAtom(new RefInset(cmd.argument)));
799                 }
800                 updateLocal(bv, true);
801                 break;
802
803         default:
804                 result = UNDISPATCHED;
805         }
806
807         mathcursor->normalize();
808         mathcursor->touch();
809
810         lyx::Assert(mathcursor);
811
812         if (mathcursor->selection() || was_selection)
813                 toggleInsetSelection(bv);
814
815         if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
816             result == UNDISPATCHED) {
817                 fitInsetCursor(bv);
818                 showInsetCursor(bv);
819                 revealCodes(bv);
820                 cmd.view()->stuffClipboard(mathcursor->grabSelection());
821         } else {
822                 releaseMathCursor(bv);
823                 bv->unlockInset(this);
824         }
825
826         return result;  // original version
827 }
828
829
830 void InsetFormulaBase::revealCodes(BufferView * bv) const
831 {
832         if (!mathcursor)
833                 return;
834         bv->owner()->message(mathcursor->info());
835
836 #if 0
837         // write something to the minibuffer
838         // translate to latex
839         mathcursor->markInsert();
840         ostringstream os;
841         write(NULL, os);
842         string str = os.str();
843         mathcursor->markErase();
844         string::size_type pos = 0;
845         string res;
846         for (string::iterator it = str.begin(); it != str.end(); ++it) {
847                 if (*it == '\n')
848                         res += ' ';
849                 else if (*it == '\0') {
850                         res += "  -X-  ";
851                         pos = it - str.begin();
852                 }
853                 else
854                         res += *it;
855         }
856         if (pos > 30)
857                 res = res.substr(pos - 30);
858         if (res.size() > 60)
859                 res = res.substr(0, 60);
860         bv->owner()->message(res);
861 #endif
862 }
863
864
865 Inset::Code InsetFormulaBase::lyxCode() const
866 {
867         return Inset::MATH_CODE;
868 }
869
870
871 int InsetFormulaBase::ylow() const
872 {
873         return yo_ - ascent(view(), font_);
874 }
875
876
877 int InsetFormulaBase::yhigh() const
878 {
879         return yo_ + descent(view(), font_);
880 }
881
882
883 int InsetFormulaBase::xlow() const
884 {
885         return xo_;
886 }
887
888
889 int InsetFormulaBase::xhigh() const
890 {
891         return xo_ + width(view(), font_);
892 }
893
894
895 /////////////////////////////////////////////////////////////////////
896
897
898 bool InsetFormulaBase::searchForward(BufferView * bv, string const & str,
899                                      bool, bool)
900 {
901 #ifdef WITH_WARNINGS
902 #warning pretty ugly
903 #endif
904         static InsetFormulaBase * lastformula = 0;
905         static MathIterator current = MathIterator(ibegin(par().nucleus()));
906         static MathArray ar;
907         static string laststr;
908
909         if (lastformula != this || laststr != str) {
910                 //lyxerr << "reset lastformula to " << this << "\n";
911                 lastformula = this;
912                 laststr = str;
913                 current = ibegin(par().nucleus());
914                 ar.clear();
915                 mathed_parse_cell(ar, str);
916         } else {
917                 ++current;
918         }
919         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
920
921         for (MathIterator it = current; it != iend(par().nucleus()); ++it) {
922                 if (it.cell().matchpart(ar, it.back().pos_)) {
923                         bv->unlockInset(bv->theLockingInset());
924                         if (!bv->lockInset(this)) {
925                                 lyxerr << "Cannot lock inset" << endl;
926                                 return false;
927                         }
928                         delete mathcursor;
929                         mathcursor = new MathCursor(this, true);
930                         metrics(bv);
931                         mathcursor->setSelection(it, ar.size());
932                         current = it;
933                         it.jump(ar.size());
934                         updateLocal(bv, false);
935                         return true;
936                 }
937         }
938
939         //lyxerr << "not found!\n";
940         lastformula = 0;
941         return false;
942 }
943
944
945 bool InsetFormulaBase::searchBackward(BufferView * bv, string const & what,
946                                       bool a, bool b)
947 {
948         lyxerr[Debug::MATHED] << "searching backward not implemented in mathed\n";
949         return searchForward(bv, what, a, b);
950 }
951
952
953 bool InsetFormulaBase::display() const
954 {
955         return par()->asHullInset() && par()->asHullInset()->display();
956 }
957
958
959 string InsetFormulaBase::selectionAsString() const
960 {
961         return mathcursor ? mathcursor->grabSelection() : string();
962 }
963
964 /////////////////////////////////////////////////////////////////////
965
966
967 void mathDispatchCreation(FuncRequest const & cmd, bool display)
968 {
969         BufferView * bv = cmd.view();
970         // use selection if available..
971         //string sel;
972         //if (action == LFUN_MATH_IMPORT_SELECTION)
973         //      sel = "";
974         //else
975
976         string sel = bv->getLyXText()->selectionAsString(bv->buffer(), false);
977
978         if (sel.empty()) {
979                 InsetFormula * f = new InsetFormula(bv);
980                 if (openNewInset(bv, f)) {
981                         bv->theLockingInset()->
982                                 localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
983                         // don't do that also for LFUN_MATH_MODE unless you want end up with
984                         // always changing to mathrm when opening an inlined inset
985                         // -- I really hate "LyXfunc overloading"...
986                         if (display)
987                                 f->localDispatch(FuncRequest(bv, LFUN_MATH_DISPLAY));
988                         f->localDispatch(FuncRequest(bv, LFUN_INSERT_MATH, cmd.argument));
989                 }
990         } else {
991                 // create a macro if we see "\\newcommand" somewhere, and an ordinary
992                 // formula otherwise
993                 InsetFormulaBase * f;
994                 if (sel.find("\\newcommand") == string::npos &&
995                                 sel.find("\\def") == string::npos)
996                         f = new InsetFormula(sel);
997                 else
998                         f = new InsetFormulaMacro(sel);
999                 bv->getLyXText()->cutSelection(bv);
1000                 openNewInset(bv, f);
1001         }
1002         cmd.message(N_("Math editor mode"));
1003 }
1004
1005
1006 void mathDispatch(FuncRequest const & cmd)
1007 {
1008         BufferView * bv = cmd.view();
1009         if (!bv->available())
1010                 return;
1011
1012         switch (cmd.action) {
1013
1014                 case LFUN_MATH_DISPLAY:
1015                         mathDispatchCreation(cmd, true);
1016                         break;
1017
1018                 case LFUN_MATH_MODE:
1019                         mathDispatchCreation(cmd, false);
1020                         break;
1021
1022                 case LFUN_MATH_IMPORT_SELECTION:
1023                         mathDispatchCreation(cmd, false);
1024                         break;
1025
1026                 case LFUN_MATH_MACRO:
1027                         if (cmd.argument.empty())
1028                                 cmd.errorMessage(N_("Missing argument"));
1029                         else {
1030                                 string s = cmd.argument;
1031                                 string const s1 = token(s, ' ', 1);
1032                                 int const na = s1.empty() ? 0 : lyx::atoi(s1);
1033                                 openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
1034                         }
1035                         break;
1036
1037                 case LFUN_GREEK:
1038                 case LFUN_INSERT_MATH:
1039                 case LFUN_INSERT_MATRIX:
1040                 case LFUN_MATH_DELIM: {
1041                         InsetFormula * f = new InsetFormula(bv);
1042                         if (openNewInset(bv, f)) {
1043                                 bv->theLockingInset()->
1044                                         localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
1045                                 bv->theLockingInset()->localDispatch(cmd);
1046                         }
1047                         break;
1048                 }
1049                 default:
1050                         break;
1051         }
1052 }