]> git.lyx.org Git - lyx.git/blobdiff - src/mathed/formulabase.C
fix #1073
[lyx.git] / src / mathed / formulabase.C
index b05790d9cafc354e4369705a03616a628fb0ba8a..d6e350fd819e31463ab17ba947b227bb9dfcb4e6 100644 (file)
 #include "Lsstream.h"
 #include "support/LAssert.h"
 
-#ifdef __GNUG__
-#pragma implementation
-#endif
 
 #include "formula.h"
 #include "formulamacro.h"
-#include "commandtags.h"
+#include "lyxrc.h"
+#include "funcrequest.h"
 #include "BufferView.h"
 #include "lyxtext.h"
-#include "lyxfunc.h"
 #include "gettext.h"
 #include "LaTeXFeatures.h"
 #include "debug.h"
 #include "math_support.h"
+#include "metricsinfo.h"
 #include "support/lstrings.h"
 #include "frontends/LyXView.h"
 #include "frontends/font_metrics.h"
@@ -39,6 +37,7 @@
 #include "Lsstream.h"
 #include "math_arrayinset.h"
 #include "math_charinset.h"
+#include "math_deliminset.h"
 #include "math_cursor.h"
 #include "math_factory.h"
 #include "math_fontinset.h"
 #include "textpainter.h"
 #include "frontends/Dialogs.h"
 #include "intl.h"
+#include "ref_inset.h"
 
 using std::endl;
 using std::ostream;
 using std::vector;
 using std::abs;
+using std::max;
 
 MathCursor * mathcursor = 0;
 
@@ -75,7 +76,7 @@ bool openNewInset(BufferView * bv, UpdatableInset * new_inset)
                delete new_inset;
                return false;
        }
-       new_inset->edit(bv, 0, 0, mouse_button::none);
+       new_inset->edit(bv, true);
        return true;
 }
 
@@ -85,14 +86,14 @@ bool openNewInset(BufferView * bv, UpdatableInset * new_inset)
 
 
 InsetFormulaBase::InsetFormulaBase()
-       : view_(0), font_(), xo_(0), yo_(0)
+       : font_(), xo_(0), yo_(0)
 {
        // This is needed as long the math parser is not re-entrant
-       MathMacroTable::builtinMacros();
+       initMath();
        //lyxerr << "sizeof MathInset: " << sizeof(MathInset) << "\n";
-       //lyxerr << "sizeof(MathMetricsInfo): " << sizeof(MathMetricsInfo) << "\n";
-       //lyxerr << "sizeof(MathCharInset): " << sizeof(MathCharInset) << "\n";
-       //lyxerr << "sizeof(LyXFont): " << sizeof(LyXFont) << "\n";
+       //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << "\n";
+       //lyxerr << "sizeof MathCharInset: " << sizeof(MathCharInset) << "\n";
+       //lyxerr << "sizeof LyXFont: " << sizeof(LyXFont) << "\n";
 }
 
 
@@ -113,7 +114,7 @@ void InsetFormulaBase::mutateToText()
                view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
 
        // remove ourselves
-       //view_->owner()->getLyXFunc()->dispatch(LFUN_ESCAPE);
+       //view_->owner()->dispatch(LFUN_ESCAPE);
 #endif
 }
 
@@ -121,19 +122,24 @@ void InsetFormulaBase::mutateToText()
 void InsetFormulaBase::handleFont
        (BufferView * bv, string const & arg, string const & font)
 {
+       // this whole function is a hack and won't work for incremental font
+       // changes...
        bv->lockedInsetStoreUndo(Undo::EDIT);
-       bool sel = mathcursor->selection();
-       if (sel)
-               updateLocal(bv, true);
-       mathcursor->handleNest(new MathFontInset(font));
-  for (string::const_iterator it = arg.begin(); it != arg.end(); ++it)
-    mathcursor->insert(*it);
-       if (!sel)
-               updateLocal(bv, false);
+       if (mathcursor->par()->name() == font)
+               mathcursor->handleFont(font);
+       else {
+               mathcursor->handleNest(createMathInset(font));
+               mathcursor->insert(arg);
+       }
+}
+
+
+BufferView * InsetFormulaBase::view() const
+{
+       return view_.lock().get();
 }
 
 
-// Check if uses AMS macros
 void InsetFormulaBase::validate(LaTeXFeatures &) const
 {}
 
@@ -148,10 +154,9 @@ void InsetFormulaBase::metrics(BufferView * bv, LyXFont const & f) const
 void InsetFormulaBase::metrics(BufferView * bv) const
 {
        if (bv)
-               view_ = bv;
-       MathMetricsInfo mi;
-       mi.view       = view_;
-       mi.base.style = display() ? LM_ST_DISPLAY : LM_ST_TEXT;
+               view_ = bv->owner()->view();
+       MetricsInfo mi;
+       mi.base.style = LM_ST_TEXT;
        mi.base.font  = font_;
        mi.base.font.setColor(LColor::math);
        par()->metrics(mi);
@@ -168,26 +173,24 @@ void InsetFormulaBase::edit(BufferView * bv, int x, int y, mouse_button::state)
 {
        if (!bv->lockInset(this))
                lyxerr[Debug::MATHED] << "Cannot lock inset!!!" << endl;
-       delete mathcursor;
+       releaseMathCursor(bv);
        mathcursor = new MathCursor(this, true);
        metrics(bv);
-       mathcursor->setPos(x, y);
-       //lyxerr << "setting pos to " << x << "," << y << "\n";
-
+       mathcursor->setPos(x + xo_, y + yo_);
        // if that is removed, we won't get the magenta box when entering an
        // inset for the first time
-       bv->updateInset(this, false);
+       bv->updateInset(this);
 }
 
 
 void InsetFormulaBase::edit(BufferView * bv, bool front)
 {
        if (!bv->lockInset(this))
-               lyxerr[Debug::MATHED] << "Cannot lock inset!!!" << endl;
-       delete mathcursor;
+               lyxerr << "Cannot lock math inset in edit call!\n";
+       releaseMathCursor(bv);
        mathcursor = new MathCursor(this, front);
        metrics(bv);
-       bv->updateInset(this, false);
+       bv->updateInset(this);
 }
 
 
@@ -196,73 +199,73 @@ void InsetFormulaBase::insetUnlock(BufferView * bv)
        if (mathcursor) {
                if (mathcursor->inMacroMode()) {
                        mathcursor->macroModeClose();
-                       updateLocal(bv, true);
+                       bv->updateInset(this);
                }
-               delete mathcursor;
-               mathcursor = 0;
+               releaseMathCursor(bv);
        }
-       bv->updateInset(this, false);
+       generatePreview();
+       bv->updateInset(this);
 }
 
 
-void InsetFormulaBase::getCursorPos(BufferView * bv, int & x, int & y) const
+void InsetFormulaBase::getCursorPos(BufferView *, int & x, int & y) const
 {
-       metrics(bv);
+       // calling metrics here destroys the cached xo,yo positions e.g. in
+       // MathParboxinset. And it would be too expensive anyway...
+       //metrics(bv);
+       if (!mathcursor) {
+               lyxerr << "getCursorPos - should not happen";
+               x = y = 0;
+               return;
+       }
        mathcursor->getPos(x, y);
-       //x -= xo_;
+       x = mathcursor->targetX();
+       x -= xo_;
        y -= yo_;
-       //lyxerr << "getCursorPos: " << x << " " << y << "\n";
+       //lyxerr << "getCursorPos: " << x << ' ' << y << endl;
 }
 
 
 void InsetFormulaBase::toggleInsetCursor(BufferView * bv)
 {
-       if (!mathcursor)
+       if (!mathcursor) {
+               lyxerr[Debug::MATHED] << "toggleInsetCursor impossible" << endl;
                return;
-
-       if (isCursorVisible())
-               bv->hideLockedInsetCursor();
-       else {
-               metrics(bv);
-               int x;
-               int y;
-               mathcursor->getPos(x, y);
-               y -= yo_;
-               int asc = 0;
-               int des = 0;
-               math_font_max_dim(font_, asc, des);
-               bv->showLockedInsetCursor(x, y, asc, des);
-               //lyxerr << "toggleInsetCursor: " << x << " " << y << "\n";
        }
-
-       toggleCursorVisible();
+       //lyxerr << "toggleInsetCursor: " << isCursorVisible() << endl;
+       if (isCursorVisible())
+               hideInsetCursor(bv);
+       else
+               showInsetCursor(bv);
 }
 
 
 void InsetFormulaBase::showInsetCursor(BufferView * bv, bool)
 {
-       if (isCursorVisible())
+       if (!mathcursor) {
+               lyxerr << "showInsetCursor impossible" << endl;
                return;
-       if (mathcursor) {
-               metrics(bv);
-               int x;
-               int y;
-               mathcursor->getPos(x, y);
-               y -= yo_;
-               int asc = 0;
-               int des = 0;
-               math_font_max_dim(font_, asc, des);
-               bv->fitLockedInsetCursor(x, y, asc, des);
-               //lyxerr << "showInsetCursor: x: " << x << " y: " << y << " yo: " << yo_ << "\n";
        }
-       toggleInsetCursor(bv);
+       if (isCursorVisible())
+               return;
+       int x, y, asc, des;
+       mathcursor->getPos(x, y);
+       math_font_max_dim(font_, asc, des);
+       bv->showLockedInsetCursor(x, y - yo_, asc, des);
+       setCursorVisible(true);
+       //lyxerr << "showInsetCursor: " << x << ' ' << y << endl;
 }
 
 
 void InsetFormulaBase::hideInsetCursor(BufferView * bv)
 {
-       if (isCursorVisible())
-               toggleInsetCursor(bv);
+       if (!mathcursor)
+               return;
+       if (!isCursorVisible())
+               return;
+       bv->hideLockedInsetCursor();
+       setCursorVisible(false);
+       //lyxerr << "hideInsetCursor: " << endl;
 }
 
 
@@ -270,20 +273,19 @@ void InsetFormulaBase::fitInsetCursor(BufferView * bv) const
 {
        if (!mathcursor)
                return;
-       
-       int const asc = font_metrics::maxAscent(font_);
-       int const desc = font_metrics::maxDescent(font_);
-       int x, y;
-
+       int x, y, asc, des;
+       math_font_max_dim(font_, asc, des);
        getCursorPos(bv, x, y);
-       bv->fitLockedInsetCursor(x, y, asc, desc);
+       //y += yo_;
+       //lyxerr << "fitInsetCursor: x: " << x << " y: " << y << " yo: " << yo_ << endl;
+       bv->fitLockedInsetCursor(x, y, asc, des);
 }
 
 
 void InsetFormulaBase::toggleInsetSelection(BufferView * bv)
 {
        if (mathcursor)
-               bv->updateInset(this, false);
+               bv->updateInset(this);
 }
 
 
@@ -293,131 +295,146 @@ vector<string> const InsetFormulaBase::getLabelList() const
 }
 
 
-void InsetFormulaBase::updateLocal(BufferView * bv, bool dirty)
+dispatch_result InsetFormulaBase::lfunMouseRelease(FuncRequest const & cmd)
 {
-       metrics(bv);
-       if (mathcursor)
-               bv->fitCursor();
-       bv->updateInset(this, dirty);
-}
-
-
-bool InsetFormulaBase::insetButtonRelease(BufferView * bv,
-                                         int /*x*/, int /*y*/, mouse_button::state button)
-{
-       //lyxerr << "insetButtonRelease: " << x << " " << y << "\n";
-
        if (!mathcursor)
-               return false;
+               return UNDISPATCHED;
+
+       BufferView * bv = cmd.view();
        hideInsetCursor(bv);
        showInsetCursor(bv);
-       bv->updateInset(this, false);
+       bv->updateInset(this);
+       //lyxerr << "lfunMouseRelease: buttons: " << cmd.button() << endl;
 
-       if (button == mouse_button::button3) {
-               // launch math panel for right mouse button
-               bv->owner()->getDialogs()->showMathPanel();
-               return true;
+       if (cmd.button() == mouse_button::button3) {
+               // try to dispatch to enclosed insets first
+               if (mathcursor->dispatch(cmd) == UNDISPATCHED) {
+                       // launch math panel for right mouse button
+                       lyxerr << "lfunMouseRelease: undispatched: " << cmd.button() << endl;
+                       bv->owner()->getDialogs().showMathPanel();
+               }
+               return DISPATCHED;
        }
-       return false;
+
+       if (cmd.button() == mouse_button::button2) {
+               mathcursor->selClear();
+               mathcursor->setPos(cmd.x + xo_, cmd.y + yo_);
+               mathcursor->insert(asArray(bv->getClipboard()));
+               bv->updateInset(this);
+               return DISPATCHED;
+       }
+
+       if (cmd.button() == mouse_button::button1) {
+               // try to dispatch to enclosed insets first
+               mathcursor->dispatch(cmd);
+               cmd.view()->stuffClipboard(mathcursor->grabSelection());
+               // try to set the cursor
+               //delete mathcursor;
+               //mathcursor = new MathCursor(this, x == 0);
+               //metrics(bv);
+               //mathcursor->setPos(x + xo_, y + yo_);
+               return DISPATCHED;
+       }
+
+       return UNDISPATCHED;
 }
 
 
-void InsetFormulaBase::insetButtonPress(BufferView * bv,
-                                       int x, int y, mouse_button::state button)
+dispatch_result InsetFormulaBase::lfunMousePress(FuncRequest const & cmd)
 {
-       //lyxerr << "insetButtonPress: "
-       //      << x << " " << y << " but: " << button << "\n";
-#if 0
-       switch (button) {
-               default:
-               case 1:
-                       // left click
-                       delete mathcursor;
-                       mathcursor = new MathCursor(this, x == 0);
-                       metrics(bv);
-                       first_x = x;
-                       first_y = y;
-                       mathcursor->selClear();
-                       mathcursor->setPos(x + xo_, y + yo_);
-                       break;
-/*
-               case 2:
-                       lyxerr << "insetButtonPress: 2\n";
-                       // insert stuff
-                       if (mathcursor) {
-                               bv->lockedInsetStoreUndo(Undo::EDIT);
-                               MathArray ar;
-                               mathcursor->selGet(ar);
-                               mathcursor->setPos(x + xo_, y + yo_);
-                               string sel =
-                                       bv->getLyXText()->selectionAsString(bv->buffer(), false);
-                               mathed_parse_cell(ar, sel);
-                               mathcursor->insert(ar);
-                       }
-                       break;
-*/
-               case 3:
-                       // launch math panel for right mouse button
-                       bv->owner()->getDialogs()->showMathPanel();
-                       break;
-       }
-#else
-       if (button == mouse_button::button1 || !mathcursor) {
-               delete mathcursor;
-               mathcursor = new MathCursor(this, x == 0);
+       BufferView * bv = cmd.view();
+       //lyxerr << "lfunMousePress: buttons: " << cmd.button() << endl;
+
+       if (!mathcursor || mathcursor->formula() != this) {
+               lyxerr[Debug::MATHED] << "re-create cursor" << endl;
+               releaseMathCursor(bv);
+               mathcursor = new MathCursor(this, cmd.x == 0);
                metrics(bv);
-               first_x = x;
-               first_y = y;
-               mathcursor->selClear();
-               mathcursor->setPos(x + xo_, y + yo_);
+               mathcursor->setPos(cmd.x + xo_, cmd.y + yo_);
        }
-#if 0
-#warning Never launch a Dialog on "Press" event ONLY on "Release" event!
-       if (button == 3) {
-               // launch math panel for right mouse button
-               bv->owner()->getDialogs()->showMathPanel();
+
+       if (cmd.button() == mouse_button::button3) {
+               mathcursor->dispatch(cmd);
+               return DISPATCHED;
        }
-#endif
-#endif
-       bv->updateInset(this, false);
+
+       if (cmd.button() == mouse_button::button1) {
+               first_x = cmd.x;
+               first_y = cmd.y;
+               mathcursor->selClear();
+               mathcursor->setPos(cmd.x + xo_, cmd.y + yo_);
+               mathcursor->dispatch(cmd);
+               return DISPATCHED;
+       }
+
+       bv->updateInset(this);
+       return DISPATCHED;
 }
 
 
-void InsetFormulaBase::insetMotionNotify(BufferView * bv,
-       int x, int y, mouse_button::state)
+dispatch_result InsetFormulaBase::lfunMouseMotion(FuncRequest const & cmd)
 {
        if (!mathcursor)
-               return;
+               return DISPATCHED;
 
-       if (abs(x - first_x) < 2 && abs(y - first_y) < 2) {
-               //lyxerr << "insetMotionNotify: ignored\n";
-               return;
-       }
-       first_x = x;
-       first_y = y;
+       if (mathcursor->dispatch(FuncRequest(cmd)) != UNDISPATCHED)
+               return DISPATCHED;
+
+       // only select with button 1
+       if (cmd.button() != mouse_button::button1)
+               return DISPATCHED;
+
+       if (abs(cmd.x - first_x) < 2 && abs(cmd.y - first_y) < 2)
+               return DISPATCHED;
+
+       first_x = cmd.x;
+       first_y = cmd.y;
 
        if (!mathcursor->selection())
                mathcursor->selStart();
 
-       //lyxerr << "insetMotionNotify: " << x + xo_ << ' ' << y + yo_
-       //      << ' ' << button << "\n";
+       BufferView * bv = cmd.view();
        hideInsetCursor(bv);
-       mathcursor->setPos(x + xo_, y + yo_);
+       mathcursor->setPos(cmd.x + xo_, cmd.y + yo_);
        showInsetCursor(bv);
-       bv->updateInset(this, false);
+       bv->updateInset(this);
+       return DISPATCHED;
 }
 
 
-UpdatableInset::RESULT
-InsetFormulaBase::localDispatch(BufferView * bv, kb_action action,
-                           string const & arg)
+dispatch_result InsetFormulaBase::localDispatch(FuncRequest const & cmd)
 {
-       //lyxerr << "InsetFormulaBase::localDispatch: act: " << action
-       //      << " arg: '" << arg << "' cursor: " << mathcursor << "\n";
+       //lyxerr << "InsetFormulaBase::localDispatch: act: " << cmd.action
+       //      << " arg: '" << cmd.argument
+       //      << " x: '" << cmd.x
+       //      << " y: '" << cmd.y
+       //      << "' button: " << cmd.button() << endl;
+
+       // delete empty mathbox (LFUN_BACKSPACE and LFUN_DELETE)
+       bool remove_inset = false;
+
+       switch (cmd.action) {
+               case LFUN_MOUSE_PRESS:
+                       //lyxerr << "Mouse single press\n";
+                       return lfunMousePress(cmd);
+               case LFUN_MOUSE_MOTION:
+                       //lyxerr << "Mouse motion\n";
+                       return lfunMouseMotion(cmd);
+               case LFUN_MOUSE_RELEASE:
+                       //lyxerr << "Mouse single release\n";
+                       return lfunMouseRelease(cmd);
+               case LFUN_MOUSE_DOUBLE:
+                       //lyxerr << "Mouse double\n";
+                       return localDispatch(FuncRequest(LFUN_WORDSEL));
+               default:
+                       break;
+       }
 
        if (!mathcursor)
                return UNDISPATCHED;
 
+       BufferView * bv    = cmd.view();
+       string argument    = cmd.argument;
        RESULT result      = DISPATCHED;
        bool sel           = false;
        bool was_macro     = mathcursor->inMacroMode();
@@ -428,99 +445,118 @@ InsetFormulaBase::localDispatch(BufferView * bv, kb_action action,
        mathcursor->normalize();
        mathcursor->touch();
 
-       switch (action) {
+       switch (cmd.action) {
 
-               // --- Cursor Movements ---------------------------------------------
+       case LFUN_MATH_MUTATE:
+       case LFUN_MATH_DISPLAY:
+       case LFUN_MATH_NUMBER:
+       case LFUN_MATH_NONUMBER:
+       case LFUN_CELL_SPLIT:
+       case LFUN_BREAKLINE:
+       case LFUN_DELETE_LINE_FORWARD:
+       case LFUN_INSERT_LABEL:
+       case LFUN_MATH_EXTERN:
+       case LFUN_TABULAR_FEATURE:
+       case LFUN_PASTESELECTION:
+       case LFUN_MATH_LIMITS:
+               bv->lockedInsetStoreUndo(Undo::EDIT);
+               mathcursor->dispatch(cmd);
+               break;
 
        case LFUN_RIGHTSEL:
                sel = true; // fall through...
-
        case LFUN_RIGHT:
                result = mathcursor->right(sel) ? DISPATCHED : FINISHED_RIGHT;
                //lyxerr << "calling scroll 20\n";
                //scroll(bv, 20);
-               updateLocal(bv, false);
                // write something to the minibuffer
                //bv->owner()->message(mathcursor->info());
                break;
 
-
        case LFUN_LEFTSEL:
                sel = true; // fall through
-
        case LFUN_LEFT:
                result = mathcursor->left(sel) ? DISPATCHED : FINISHED;
-               updateLocal(bv, false);
                break;
 
-
        case LFUN_UPSEL:
-               sel = true;
-
+               sel = true; // fall through
        case LFUN_UP:
                result = mathcursor->up(sel) ? DISPATCHED : FINISHED_UP;
-               updateLocal(bv, false);
                break;
 
-
        case LFUN_DOWNSEL:
-               sel = true;
-
+               sel = true; // fall through
        case LFUN_DOWN:
                result = mathcursor->down(sel) ? DISPATCHED : FINISHED_DOWN;
-               updateLocal(bv, false);
                break;
 
-       case LFUN_HOMESEL:
-               sel = true;
+       case LFUN_WORDSEL:
+               mathcursor->home(false);
+               mathcursor->end(true);
+               break;
+
+       case LFUN_UP_PARAGRAPHSEL:
+       case LFUN_UP_PARAGRAPH:
+       case LFUN_DOWN_PARAGRAPHSEL:
+       case LFUN_DOWN_PARAGRAPH:
+               result = FINISHED;
+               break;
 
+       case LFUN_HOMESEL:
+       case LFUN_WORDLEFTSEL:
+               sel = true; // fall through
        case LFUN_HOME:
-               mathcursor->home(sel);
-               updateLocal(bv, false);
+       case LFUN_WORDLEFT:
+               result = mathcursor->home(sel) ? DISPATCHED : FINISHED;
                break;
 
        case LFUN_ENDSEL:
-               sel = true;
-
+       case LFUN_WORDRIGHTSEL:
+               sel = true; // fall through
        case LFUN_END:
-               mathcursor->end(sel);
-               updateLocal(bv, false);
+       case LFUN_WORDRIGHT:
+               result = mathcursor->end(sel) ? DISPATCHED : FINISHED_RIGHT;
                break;
 
-       case LFUN_DELETE_LINE_FORWARD:
-               bv->lockedInsetStoreUndo(Undo::DELETE);
-               mathcursor->delLine();
-               updateLocal(bv, true);
+       case LFUN_PRIORSEL:
+       case LFUN_PRIOR:
+       case LFUN_BEGINNINGBUFSEL:
+       case LFUN_BEGINNINGBUF:
+               result = FINISHED;
                break;
 
-       case LFUN_TAB:
-               mathcursor->idxNext();
-               updateLocal(bv, false);
+       case LFUN_NEXTSEL:
+       case LFUN_NEXT:
+       case LFUN_ENDBUFSEL:
+       case LFUN_ENDBUF:
+               result = FINISHED_RIGHT;
                break;
 
-       case LFUN_SHIFT_TAB:
-               mathcursor->idxPrev();
-               updateLocal(bv, false);
+       case LFUN_CELL_FORWARD:
+               mathcursor->idxNext();
                break;
 
-       case LFUN_TABINSERT:
-               bv->lockedInsetStoreUndo(Undo::EDIT);
-               mathcursor->splitCell();
-               updateLocal(bv, true);
+       case LFUN_CELL_BACKWARD:
+               mathcursor->idxPrev();
                break;
 
        case LFUN_DELETE_WORD_BACKWARD:
        case LFUN_BACKSPACE:
-               bv->lockedInsetStoreUndo(Undo::DELETE);
-               mathcursor->backspace();
-               bv->updateInset(this, true);
+               bv->lockedInsetStoreUndo(Undo::EDIT);
+               if (!mathcursor->backspace()) {
+                       result = FINISHED;
+                       remove_inset = true;
+               }
                break;
 
        case LFUN_DELETE_WORD_FORWARD:
        case LFUN_DELETE:
-               bv->lockedInsetStoreUndo(Undo::DELETE);
-               mathcursor->erase();
-               bv->updateInset(this, true);
+               bv->lockedInsetStoreUndo(Undo::EDIT);
+               if (!mathcursor->erase()) {
+                       result = FINISHED;
+                       remove_inset = true;
+               }
                break;
 
        //    case LFUN_GETXY:
@@ -531,46 +567,44 @@ InsetFormulaBase::localDispatch(BufferView * bv, kb_action action,
                lyxerr << "LFUN_SETXY broken!\n";
                int x = 0;
                int y = 0;
-               istringstream is(arg.c_str());
+               istringstream is(cmd.argument.c_str());
                is >> x >> y;
                mathcursor->setPos(x, y);
-               updateLocal(bv, false);
                break;
        }
 
-       case LFUN_PASTE:
+       case LFUN_PASTE: {
+               int n = 0;
+               istringstream is(cmd.argument.c_str());
+               is >> n;
                if (was_macro)
                        mathcursor->macroModeClose();
                bv->lockedInsetStoreUndo(Undo::EDIT);
-               mathcursor->selPaste();
-               updateLocal(bv, true);
+               mathcursor->selPaste(n);
                break;
+       }
 
        case LFUN_CUT:
                bv->lockedInsetStoreUndo(Undo::DELETE);
                mathcursor->selCut();
-               updateLocal(bv, true);
                break;
 
        case LFUN_COPY:
                mathcursor->selCopy();
                break;
 
-       case LFUN_WORDRIGHTSEL:
-       case LFUN_WORDLEFTSEL:
-               break;
 
        // Special casing for superscript in case of LyX handling
        // dead-keys:
        case LFUN_CIRCUMFLEX:
-               if (arg.empty()) {
+               if (cmd.argument.empty()) {
                        // do superscript if LyX handles
                        // deadkeys
                        bv->lockedInsetStoreUndo(Undo::EDIT);
                        mathcursor->script(true);
-                       updateLocal(bv, true);
                }
                break;
+
        case LFUN_UMLAUT:
        case LFUN_ACUTE:
        case LFUN_GRAVE:
@@ -588,64 +622,55 @@ InsetFormulaBase::localDispatch(BufferView * bv, kb_action action,
                break;
 
        //  Math fonts
-       case LFUN_GREEK_TOGGLE: handleFont(bv, arg, "lyxgreek"); break;
-       case LFUN_BOLD:         handleFont(bv, arg, "textbf"); break;
-       case LFUN_SANS:         handleFont(bv, arg, "textsf"); break;
-       case LFUN_EMPH:         handleFont(bv, arg, "mathcal"); break;
-       case LFUN_ROMAN:        handleFont(bv, arg, "mathrm"); break;
-       case LFUN_CODE:         handleFont(bv, arg, "texttt"); break;
-       case LFUN_FRAK:         handleFont(bv, arg, "mathfrak"); break;
-       case LFUN_ITAL:         handleFont(bv, arg, "mathit"); break;
-       case LFUN_NOUN:         handleFont(bv, arg, "mathbb"); break;
-       case LFUN_DEFAULT:      handleFont(bv, arg, "textnormal"); break;
-       case LFUN_FREE:         handleFont(bv, arg, "textrm"); break;
-
-       case LFUN_GREEK:
-               handleFont(bv, arg, "lyxgreek1");
-               if (arg.size())
-                       mathcursor->interpret(arg);
-               break;
+       case LFUN_BOLD:         handleFont(bv, cmd.argument, "mathbf"); break;
+       case LFUN_SANS:         handleFont(bv, cmd.argument, "mathsf"); break;
+       case LFUN_EMPH:         handleFont(bv, cmd.argument, "mathcal"); break;
+       case LFUN_ROMAN:        handleFont(bv, cmd.argument, "mathrm"); break;
+       case LFUN_CODE:         handleFont(bv, cmd.argument, "texttt"); break;
+       case LFUN_FRAK:         handleFont(bv, cmd.argument, "mathfrak"); break;
+       case LFUN_ITAL:         handleFont(bv, cmd.argument, "mathit"); break;
+       case LFUN_NOUN:         handleFont(bv, cmd.argument, "mathbb"); break;
+       case LFUN_FREEFONT_APPLY:  handleFont(bv, cmd.argument, "textrm"); break;
+       case LFUN_DEFAULT:      handleFont(bv, cmd.argument, "textnormal"); break;
 
        case LFUN_MATH_MODE:
-               if (mathcursor->inMathMode()) {
-                       handleFont(bv, arg, "textrm");
-               } else {
-                       mathcursor->niceInsert(MathAtom(new MathHullInset(LM_OT_SIMPLE)));
-                       updateLocal(bv, true);
-               }
+               if (mathcursor->currentMode() == MathInset::TEXT_MODE)
+                       mathcursor->niceInsert(MathAtom(new MathHullInset("simple")));
+               else
+                       handleFont(bv, cmd.argument, "textrm");
                //bv->owner()->message(_("math text mode toggled"));
                break;
 
-       case LFUN_MATH_LIMITS:
-               bv->lockedInsetStoreUndo(Undo::EDIT);
-               if (mathcursor->toggleLimits())
-                       updateLocal(bv, true);
-               break;
-
        case LFUN_MATH_SIZE:
 #if 0
                if (!arg.empty()) {
                        bv->lockedInsetStoreUndo(Undo::EDIT);
                        mathcursor->setSize(arg);
-                       updateLocal(bv, true);
                }
 #endif
                break;
 
-       case LFUN_INSERT_MATRIX:
-               if (!arg.empty()) {
-                       bv->lockedInsetStoreUndo(Undo::EDIT);
-                       mathcursor->interpret("matrix " + arg);
-                       updateLocal(bv, true);
-               }
+       case LFUN_INSERT_MATRIX: {
+               bv->lockedInsetStoreUndo(Undo::EDIT);
+               unsigned int m = 1;
+               unsigned int n = 1;
+               string v_align;
+               string h_align;
+               istringstream is(STRCONV(argument));
+               is >> m >> n >> v_align >> h_align;
+               m = max(1u, m);
+               n = max(1u, n);
+               v_align += 'c';
+               mathcursor->niceInsert(
+                       MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
                break;
+       }
 
        case LFUN_SUPERSCRIPT:
        case LFUN_SUBSCRIPT:
        {
                bv->lockedInsetStoreUndo(Undo::EDIT);
-               mathcursor->script(action == LFUN_SUPERSCRIPT);
-               updateLocal(bv, true);
+               mathcursor->script(cmd.action == LFUN_SUPERSCRIPT);
                break;
        }
 
@@ -653,7 +678,7 @@ InsetFormulaBase::localDispatch(BufferView * bv, kb_action action,
        {
                //lyxerr << "formulabase::LFUN_MATH_DELIM, arg: '" << arg << "'\n";
                string ls;
-               string rs = split(arg, ls, ' ');
+               string rs = split(cmd.argument, ls, ' ');
                // Reasonable default values
                if (ls.empty())
                        ls = '(';
@@ -661,16 +686,14 @@ InsetFormulaBase::localDispatch(BufferView * bv, kb_action action,
                        rs = ')';
 
                bv->lockedInsetStoreUndo(Undo::EDIT);
-               mathcursor->handleDelim(ls, rs);
-               updateLocal(bv, true);
+               mathcursor->handleNest(MathAtom(new MathDelimInset(ls, rs)));
                break;
        }
 
        case LFUN_PROTECTEDSPACE:
        case LFUN_MATH_SPACE:
                bv->lockedInsetStoreUndo(Undo::EDIT);
-               mathcursor->insert(MathAtom(new MathSpaceInset(1)));
-               updateLocal(bv, true);
+               mathcursor->insert(MathAtom(new MathSpaceInset(",")));
                break;
 
        case LFUN_UNDO:
@@ -678,59 +701,38 @@ InsetFormulaBase::localDispatch(BufferView * bv, kb_action action,
                break;
 
 
-       case LFUN_MATH_HALIGN:
-       case LFUN_MATH_VALIGN:
-       case LFUN_MATH_ROW_INSERT:
-       case LFUN_MATH_ROW_DELETE:
-       case LFUN_MATH_COLUMN_INSERT:
-       case LFUN_MATH_COLUMN_DELETE:
-       {
-               MathInset::idx_type idx = 0;
-               MathGridInset * p = mathcursor ? mathcursor->enclosingGrid(idx) : 0;
-               if (p) {
-                       mathcursor->popToEnclosingGrid();
-                       bv->lockedInsetStoreUndo(Undo::EDIT);
-                       char align = arg.size() ? arg[0] : 'c';
-                       switch (action) {
-                               case LFUN_MATH_HALIGN: p->halign(align, p->col(idx)); break;
-                               case LFUN_MATH_VALIGN: p->valign(align); break;
-                               case LFUN_MATH_ROW_INSERT: p->addRow(p->row(idx)); break;
-                               case LFUN_MATH_ROW_DELETE: p->delRow(p->row(idx)); break;
-                               case LFUN_MATH_COLUMN_INSERT: p->addFancyCol(p->col(idx)); break;
-                               case LFUN_MATH_COLUMN_DELETE: p->delFancyCol(p->col(idx)); break;
-                               default: ;
-                       }
-                       updateLocal(bv, true);
-               }
-               break;
-       }
-
        case LFUN_EXEC_COMMAND:
                result = UNDISPATCHED;
                break;
 
-       case LFUN_BREAKPARAGRAPH:
-       case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
-               //lyxerr << "LFUN ignored\n";
-               break;
-
        case LFUN_INSET_ERT:
                // interpret this as if a backslash was typed
                bv->lockedInsetStoreUndo(Undo::EDIT);
                mathcursor->interpret('\\');
-               updateLocal(bv, true);
                break;
 
-       case -1:
+       case LFUN_BREAKPARAGRAPH:
+       case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
+       case LFUN_BREAKPARAGRAPH_SKIP:
+               argument = "\n";
+               // fall through
+
+// FIXME: We probably should swap parts of "math-insert" and "self-insert"
+// handling such that "self-insert" works on "arbitrary stuff" too, and
+// math-insert only handles special math things like "matrix".
        case LFUN_INSERT_MATH:
+               bv->lockedInsetStoreUndo(Undo::EDIT);
+               mathcursor->niceInsert(argument);
+               break;
+
+       case -1:
        case LFUN_SELFINSERT:
-               if (!arg.empty()) {
+               if (!argument.empty()) {
                        bv->lockedInsetStoreUndo(Undo::EDIT);
-                       if (arg.size() == 1)
-                               result = mathcursor->interpret(arg[0]) ? DISPATCHED : FINISHED_RIGHT;
+                       if (argument.size() == 1)
+                               result = mathcursor->interpret(argument[0]) ? DISPATCHED : FINISHED_RIGHT;
                        else
-                               result = mathcursor->interpret(arg) ? DISPATCHED : FINISHED_RIGHT;
-                       updateLocal(bv, true);
+                               mathcursor->insert(asArray(argument));
                }
                break;
 
@@ -747,13 +749,51 @@ InsetFormulaBase::localDispatch(BufferView * bv, kb_action action,
 
        case LFUN_INSET_TOGGLE:
                mathcursor->insetToggle();
-               updateLocal(bv, true);
                break;
 
+       case LFUN_DIALOG_SHOW_NEW_INSET: {
+               string const & name = argument;
+               string data;
+               if (name == "ref") {
+                       RefInset tmp(name);
+                       data = tmp.createDialogStr(name);
+               }
+
+               if (data.empty())
+                       result = UNDISPATCHED;
+               else {
+                       bv->owner()->getDialogs().show(name, data, 0);
+               }
+       }
+       break;
+
+       case LFUN_INSET_APPLY: {
+               string const name = cmd.getArg(0);
+               InsetBase * base =
+                       bv->owner()->getDialogs().getOpenInset(name);
+
+               if (base) {
+                       FuncRequest fr(bv, LFUN_INSET_MODIFY, cmd.argument);
+                       result = base->localDispatch(fr);
+               } else {
+                       MathArray ar;
+                       if (createMathInset_fromDialogStr(cmd.argument, ar)) {
+                               mathcursor->insert(ar);
+                               result = DISPATCHED;
+                       } else {
+                               result = UNDISPATCHED;
+                       }
+               }
+       }
+       break;
+
        default:
                result = UNDISPATCHED;
        }
 
+       if (result == DISPATCHED)
+               bv->updateInset(this);
+
        mathcursor->normalize();
        mathcursor->touch();
 
@@ -763,12 +803,17 @@ InsetFormulaBase::localDispatch(BufferView * bv, kb_action action,
                toggleInsetSelection(bv);
 
        if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
-           result == UNDISPATCHED)
+           result == UNDISPATCHED) {
+               fitInsetCursor(bv);
                showInsetCursor(bv);
-       else
+               revealCodes(bv);
+               cmd.view()->stuffClipboard(mathcursor->grabSelection());
+       } else {
+               releaseMathCursor(bv);
                bv->unlockInset(this);
-
-       revealCodes(bv);
+               if (remove_inset)
+                       bv->owner()->dispatch(FuncRequest(LFUN_DELETE));
+       }
 
        return result;  // original version
 }
@@ -817,13 +862,13 @@ Inset::Code InsetFormulaBase::lyxCode() const
 
 int InsetFormulaBase::ylow() const
 {
-       return yo_ - ascent(view_, font_);
+       return yo_ - ascent(view(), font_);
 }
 
 
 int InsetFormulaBase::yhigh() const
 {
-       return yo_ + descent(view_, font_);
+       return yo_ + descent(view(), font_);
 }
 
 
@@ -835,7 +880,7 @@ int InsetFormulaBase::xlow() const
 
 int InsetFormulaBase::xhigh() const
 {
-       return xo_ + width(view_, font_);
+       return xo_ + width(view(), font_);
 }
 
 
@@ -866,7 +911,7 @@ bool InsetFormulaBase::searchForward(BufferView * bv, string const & str,
        //lyxerr << "searching '" << str << "' in " << this << ar << endl;
 
        for (MathIterator it = current; it != iend(par().nucleus()); ++it) {
-               if (it.cell().matchpart(ar, it.position().pos_)) {
+               if (it.cell().matchpart(ar, it.back().pos_)) {
                        bv->unlockInset(bv->theLockingInset());
                        if (!bv->lockInset(this)) {
                                lyxerr << "Cannot lock inset" << endl;
@@ -875,10 +920,10 @@ bool InsetFormulaBase::searchForward(BufferView * bv, string const & str,
                        delete mathcursor;
                        mathcursor = new MathCursor(this, true);
                        metrics(bv);
-                       mathcursor->setSelection(it.cursor(), ar.size());
+                       mathcursor->setSelection(it, ar.size());
                        current = it;
                        it.jump(ar.size());
-                       updateLocal(bv, false);
+                       bv->updateInset(this);
                        return true;
                }
        }
@@ -892,139 +937,108 @@ bool InsetFormulaBase::searchForward(BufferView * bv, string const & str,
 bool InsetFormulaBase::searchBackward(BufferView * bv, string const & what,
                                      bool a, bool b)
 {
-       lyxerr << "searching backward not implemented in mathed" << endl;
+       lyxerr[Debug::MATHED] << "searching backward not implemented in mathed\n";
        return searchForward(bv, what, a, b);
 }
 
 
-/////////////////////////////////////////////////////////////////////
-
-
-void mathDispatchCreation(BufferView * bv, string const & arg, bool display)
+bool InsetFormulaBase::display() const
 {
-       if (bv->available()) {
-               // use selection if available..
-               //string sel;
-               //if (action == LFUN_MATH_IMPORT_SELECTION)
-               //      sel = "";
-               //else
-
-               string sel = bv->getLyXText()->selectionAsString(bv->buffer(), false);
-
-               InsetFormulaBase * f;
-               if (sel.empty()) {
-                       f = new InsetFormula;
-                       if (openNewInset(bv, f)) {
-                               // don't do that also for LFUN_MATH_MODE unless you want end up with
-                               // always changing to mathrm when opening an inlined inset
-                               // -- I really hate "LyXfunc overloading"...
-                               if (display)
-                                       f->localDispatch(bv, LFUN_MATH_DISPLAY, string());
-                               f->localDispatch(bv, LFUN_INSERT_MATH, arg);
-                       }
-               } else {
-                       // create a macro if we see "\\newcommand" somewhere, and an ordinary
-                       // formula otherwise
-                       if (sel.find("\\newcommand") == string::npos &&
-                                 sel.find("\\def") == string::npos)
-                       {
-                               f = new InsetFormula(sel);
-                       } else {
-                               string name;
-                               if (!mathed_parse_macro(name, sel))
-                                       return;
-                               f = new InsetFormulaMacro(sel);
-                       }
-                       bv->getLyXText()->cutSelection(bv);
-                       openNewInset(bv, f);
-               }
-       }
-       bv->owner()->getLyXFunc()->setMessage(N_("Math editor mode"));
+       return par()->asHullInset() && par()->asHullInset()->display();
 }
 
 
-void mathDispatchMathDisplay(BufferView * bv, string const & arg)
+string InsetFormulaBase::selectionAsString() const
 {
-       mathDispatchCreation(bv, arg, true);
+       return mathcursor ? mathcursor->grabSelection() : string();
 }
 
-
-void mathDispatchMathMode(BufferView * bv, string const & arg)
-{
-       mathDispatchCreation(bv, arg, false);
-}
+/////////////////////////////////////////////////////////////////////
 
 
-void mathDispatchMathImportSelection(BufferView * bv, string const & arg)
+void mathDispatchCreation(FuncRequest const & cmd, bool display)
 {
-       mathDispatchCreation(bv, arg, true);
-}
+       BufferView * bv = cmd.view();
+       // use selection if available..
+       //string sel;
+       //if (action == LFUN_MATH_IMPORT_SELECTION)
+       //      sel = "";
+       //else
 
+       string sel = bv->getLyXText()->selectionAsString(bv->buffer(), false);
 
-void mathDispatchMathMacro(BufferView * bv, string const & arg)
-{
-       if (bv->available()) {
-               if (arg.empty())
-                       bv->owner()->getLyXFunc()->setErrorMessage(N_("Missing argument"));
-               else {
-                       string s = arg;
-                       string const s1 = token(s, ' ', 1);
-                       int const na = s1.empty() ? 0 : lyx::atoi(s1);
-                       openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
+       if (sel.empty()) {
+               InsetFormula * f = new InsetFormula(bv);
+               if (openNewInset(bv, f)) {
+                       bv->theLockingInset()->
+                               localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
+                       // don't do that also for LFUN_MATH_MODE unless you want end up with
+                       // always changing to mathrm when opening an inlined inset
+                       // -- I really hate "LyXfunc overloading"...
+                       if (display)
+                               f->localDispatch(FuncRequest(bv, LFUN_MATH_DISPLAY));
+                       f->localDispatch(FuncRequest(bv, LFUN_INSERT_MATH, cmd.argument));
                }
+       } else {
+               // create a macro if we see "\\newcommand" somewhere, and an ordinary
+               // formula otherwise
+               InsetFormulaBase * f;
+               if (sel.find("\\newcommand") == string::npos &&
+                               sel.find("\\def") == string::npos)
+                       f = new InsetFormula(sel);
+               else
+                       f = new InsetFormulaMacro(sel);
+               bv->getLyXText()->cutSelection(bv);
+               openNewInset(bv, f);
        }
+       cmd.message(N_("Math editor mode"));
 }
 
 
-void mathDispatchMathDelim(BufferView * bv, string const & arg)
+void mathDispatch(FuncRequest const & cmd)
 {
-       if (bv->available()) {
-               if (openNewInset(bv, new InsetFormula))
-                       bv->theLockingInset()->localDispatch(bv, LFUN_MATH_DELIM, arg);
-       }
-}
+       BufferView * bv = cmd.view();
+       if (!bv->available())
+               return;
 
+       switch (cmd.action) {
 
-void mathDispatchInsertMatrix(BufferView * bv, string const & arg)
-{
-       if (bv->available()) {
-               if (openNewInset(bv, new InsetFormula))
-                       bv->theLockingInset()->localDispatch(bv, LFUN_INSERT_MATRIX, arg);
-       }
-}
+               case LFUN_MATH_DISPLAY:
+                       mathDispatchCreation(cmd, true);
+                       break;
 
+               case LFUN_MATH_MODE:
+                       mathDispatchCreation(cmd, false);
+                       break;
 
-void mathDispatchInsertMath(BufferView * bv, string const & arg)
-{
-       if (bv->available()) {
-               if (arg.size() && arg[0] == '\\') {
-                       InsetFormula * f = new InsetFormula(arg);
-                       if (!bv->insertInset(f))
-                               delete f;
-                       else if (!mathcursor) // hotfix
-                               bv->getLyXText()->cursorRight(bv);
-               } else {
-                       mathDispatchMathMode(bv, arg);
-               }
-       }
-}
+               case LFUN_MATH_IMPORT_SELECTION:
+                       mathDispatchCreation(cmd, false);
+                       break;
 
+               case LFUN_MATH_MACRO:
+                       if (cmd.argument.empty())
+                               cmd.errorMessage(N_("Missing argument"));
+                       else {
+                               string s = cmd.argument;
+                               string const s1 = token(s, ' ', 1);
+                               int const na = s1.empty() ? 0 : lyx::atoi(s1);
+                               openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
+                       }
+                       break;
 
-void mathDispatchGreek(BufferView * bv, string const & arg)
-{
-       if (bv->available()) {
-               InsetFormula * f = new InsetFormula;
-               if (openNewInset(bv, f)) {
-                       bv->theLockingInset()->localDispatch(bv, LFUN_GREEK, arg);
-                       bv->unlockInset(f);
+               case LFUN_INSERT_MATH:
+               case LFUN_INSERT_MATRIX:
+               case LFUN_MATH_DELIM: {
+                       InsetFormula * f = new InsetFormula(bv);
+                       if (openNewInset(bv, f)) {
+                               bv->theLockingInset()->
+                                       localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
+                               bv->theLockingInset()->localDispatch(cmd);
+                       }
+                       break;
                }
+
+               default:
+                       break;
        }
 }
-
-
-void mathDispatch(BufferView *, kb_action, string const &)
-{}
-
-
-void mathDispatch(BufferView *, string const &)
-{}