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