]> git.lyx.org Git - lyx.git/blobdiff - src/mathed/math_cursor.C
cursor up/down behind scripts fixed
[lyx.git] / src / mathed / math_cursor.C
index be1b146fc9bbd8408ffc49eddb003dc5737fdb7a..ca2b35904f9b371e1554971a37f62b03d1bc05e3 100644 (file)
 /*
-*  File:        math_cursor.C
-*  Purpose:     Interaction for mathed
-*  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
-*  Created:     January 1996
-*  Description: Math interaction for a WYSIWYG math editor.
-*
-*  Dependencies: Xlib, XForms
-*
-*  Copyright: 1996, Alejandro Aguilar Sierra
-*
-*   Version: 0.8beta, Mathed & Lyx project.
-*
-*   You are free to use and modify this code under the terms of
-*   the GNU General Public Licence version 2 or later.
-*/
+ *  File:        math_cursor.C
+ *  Purpose:     Interaction for mathed
+ *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
+ *  Created:     January 1996
+ *  Description: Math interaction for a WYSIWYG math editor.
+ *
+ *  Dependencies: Xlib, XForms
+ *
+ *  Copyright: 1996, Alejandro Aguilar Sierra
+ *
+ *   Version: 0.8beta, Math & Lyx project.
+ *
+ *   You are free to use and modify this code under the terms of
+ *   the GNU General Public Licence version 2 or later.
+ */
 
 #ifdef __GNUG__
 #pragma implementation
 #endif
 
 #include <config.h>
-#include FORMS_H_LOCATION
-#include "math_inset.h"
-#include "math_parser.h"
-#include "math_cursor.h"
-#include "math_macro.h"
-#include "math_macrotable.h"
-#include "math_root.h"
+#include <algorithm>
+#include <cctype>
+
 #include "support/lstrings.h"
+#include "support/LAssert.h"
 #include "debug.h"
 #include "LColor.h"
 #include "Painter.h"
+#include "support.h"
+#include "formulabase.h"
+#include "math_cursor.h"
+#include "math_factory.h"
+#include "math_arrayinset.h"
+#include "math_charinset.h"
+#include "math_deliminset.h"
 #include "math_matrixinset.h"
-#include "math_rowst.h"
+#include "math_scriptinset.h"
 #include "math_spaceinset.h"
-#include "math_funcinset.h"
-#include "math_bigopinset.h"
-#include "math_fracinset.h"
-#include "math_decorationinset.h"
-#include "math_dotsinset.h"
-#include "math_accentinset.h"
-#include "math_macrotemplate.h"
-#include "mathed/support.h"
+#include "math_specialcharinset.h"
+#include "math_parser.h"
+
+#define FILEDEBUG 0
 
 using std::endl;
+using std::min;
+using std::max;
+using std::swap;
+using std::isalnum;
 
 namespace {
 
-MathedArray selarray;
-
-// This was very smaller, I'll change it later
-inline
-bool IsMacro(short tok, int id)
+struct Selection
 {
-       return tok != LM_TK_STACK &&
-              tok != LM_TK_FRAC &&
-              tok != LM_TK_SQRT &&
-              tok != LM_TK_WIDE &&
-              tok != LM_TK_SPACE &&
-              tok != LM_TK_DOTS &&
-              tok != LM_TK_FUNCLIM &&
-              tok != LM_TK_BIGSYM &&
-              tok != LM_TK_ACCENT &&
-              !(tok == LM_TK_SYM && id < 255);
-}
-
-int const MAX_STACK_ITEMS = 32;
-
-struct MathStackXIter {
-       std::vector<MathedXIter> item;
-       int i;
-
-       MathStackXIter(int n = MAX_STACK_ITEMS)
-               : item(n), i(0) {
+       void grab(MathCursor const & cursor)
+       {
+               data_.clear();
+               MathCursorPos i1;
+               MathCursorPos i2;
+               cursor.getSelection(i1, i2); 
+               if (i1.idx_ == i2.idx_)
+                       data_.push_back(MathArray(i1.cell(), i1.pos_, i2.pos_));
+               else {
+                       std::vector<MathInset::idx_type> indices =
+                               (*i1.par_)->idxBetween(i1.idx_, i2.idx_);
+                       for (MathInset::idx_type i = 0; i < indices.size(); ++i)
+                               data_.push_back(i1.cell(indices[i]));
+               }
        }
 
-       MathedXIter * push() {
-               return &item[i++];
+       void erase(MathCursor & cursor)
+       {
+               MathCursorPos i1;
+               MathCursorPos i2;
+               cursor.getSelection(i1, i2); 
+               if (i1.idx_ == i2.idx_) {
+                       i1.cell().erase(i1.pos_, i2.pos_);
+               } else {
+                       std::vector<MathInset::idx_type> indices =
+                               (*i1.par_)->idxBetween(i1.idx_, i2.idx_);
+                       for (unsigned i = 0; i < indices.size(); ++i)
+                               i1.cell(indices[i]).erase();
+               }
+               cursor.cursor() = i1;
        }
 
-       MathedXIter * pop() {
-    --i;
-               return &item[i - 1];
+       void paste(MathCursor & cursor) const
+       {
+               MathArray ar = glue();
+               cursor.paste(ar);
        }
 
-       MathedXIter * Item(int idx) {
-               if (idx + 1 > i)
-                       lyxerr << "Wrong index: " << idx << " i: " << i << endl;
-               return &item[i - idx - 1];
+       // glues selection to one cell
+       MathArray glue() const
+       {
+               MathArray ar;
+               for (unsigned i = 0; i < data_.size(); ++i)
+                       ar.push_back(data_[i]);
+               return ar;
        }
 
-       void Reset() {
-               i = 0;
+       void clear()
+       {
+               data_.clear();
        }
 
-       bool Full() {
-               return i >= MAX_STACK_ITEMS;
-       }
+       std::vector<MathArray> data_;
+};
 
-       bool Empty() {
-               return i <= 1;
-       }
 
-       int Level() { return i; }
+Selection theSelection;
 
-} mathstk, selstk;
 
-} // namespace anon
+#if FILEDEBUG
+std::ostream & operator<<(std::ostream & os, MathCursorPos const & p)
+{
+       os << "(par: " << p.par_ << " idx: " << p.idx_ << " pos: " << p.pos_ << ")";
+       return os;
+}
+#endif
 
+}
 
-/***----------------  Mathed Cursor  ---------------------------***/
 
-MathedCursor::MathedCursor(MathParInset * p) // : par(p)
+MathCursor::MathCursor(InsetFormulaBase * formula, bool left)
+       : formula_(formula), lastcode_(LM_TC_VAR), selection_(false)
 {
-       accent   = 0;
-       anchor   = 0;
-       lastcode = LM_TC_MIN;
-       SetPar(p);
-       if (!MathMacroTable::built)
-               MathMacroTable::mathMTable.builtinMacros();
+       left ? first() : last();
 }
 
 
-void MathedCursor::SetPar(MathParInset * p)
+void MathCursor::push(MathAtom & t)
 {
-       macro_mode = false;
-       selection  = false; // not SelClear() ?
-       mathstk.Reset();
-       cursor = mathstk.push();
-       par = p;
-       cursor->SetData(par);
+       //cerr << "Entering atom "; t->write(cerr, false); cerr << " left\n";
+       MathCursorPos p;
+       p.par_ = &t;
+       Cursor_.push_back(p);
 }
 
 
-void MathedCursor::draw(Painter & pain, int x, int y)
+void MathCursor::pushLeft(MathAtom & t)
 {
-       //    lyxerr << "Cursor[" << x << " " << y << "] ";
-       //win = pm;    // win = (mathedCanvas) ? mathedCanvas: pm;
+       //cerr << "Entering atom "; t->write(cerr, false); cerr << " left\n";
+       push(t);
+       t->idxFirst(idx(), pos());
+}
 
-       par->Metrics();
-       int w = par->Width() + 2;
-       int a = par->Ascent() + 1;
-       int h = par->Height() + 1;
 
-       if (par->GetType() > LM_OT_PAR) {
-               a += 4;
-               h += 8;
-       }
+void MathCursor::pushRight(MathAtom & t)
+{
+       //cerr << "Entering atom "; t->write(cerr, false); cerr << " right\n";
+       posLeft();
+       push(t);
+       t->idxLast(idx(), pos());
+}
 
-       pain.rectangle(x - 1, y - a, w, h, LColor::mathframe);
 
-       par->draw(pain, x, y);
-       cursor->Adjust();
+bool MathCursor::popLeft()
+{
+       //cerr << "Leaving atom "; par()->write(cerr, false); cerr << " left\n";
+       if (Cursor_.size() <= 1)
+               return false;
+       //if (nextInset())
+       //      nextInset()->removeEmptyScripts();
+       Cursor_.pop_back();
+       //if (nextAtom())
+       //      nextAtom()->removeEmptyScripts();
+       return true;
 }
 
 
-void MathedCursor::Redraw(Painter & pain)
+bool MathCursor::popRight()
 {
-       lyxerr[Debug::MATHED] << "Mathed: Redrawing!" << endl;
-       par->Metrics();
-       int w = par->Width();
-       int h = par->Height();
-       int x;
-       int y;
-       par->GetXY(x, y);
-       //mathed_set_font(LM_TC_VAR, 1);
-       pain.fillRectangle(x, y - par->Ascent(),
-       x + w, y - par->Ascent() + h,
-       LColor::mathbg);
-       par->draw(pain, x, y);
+       //cerr << "Leaving atom "; par()->write(cerr, false); cerr << " right\n";
+       if (Cursor_.size() <= 1)
+               return false;
+       //if (nextInset())
+       //      nextInset()->removeEmptyScripts();
+       Cursor_.pop_back();
+       //if (nextInset())
+       //      nextInset()->removeEmptyScripts();
+       posRight();
+       return true;
 }
 
 
-bool MathedCursor::Left(bool sel)
+
+#if FILEDEBUG
+void MathCursor::dump(char const * what) const
 {
-       if (macro_mode) {
-               // was MacroModeBack()
-               if (!imacro->GetName().empty()) {
-                       imacro->SetName(imacro->GetName()
-                                       .substr(0, imacro->GetName()
-                                               .length() - 1));
-                       imacro->Metrics();
-               } else
-                       MacroModeClose();
-               return true;
-       }
+       lyxerr << "MC: " << what << "\n";
+       for (unsigned i = 0; i < Cursor_.size(); ++i)
+               lyxerr << "  i: " << i 
+                       << " Cursor: pos: " << Cursor_[i].pos_
+                       << " idx: " << Cursor_[i].idx_
+                       << " par: " << Cursor_[i].par_ << "\n";
+
+       for (unsigned i = 0; i < Anchor_.size(); ++i)
+               lyxerr << "  i: " << i 
+                       << " Anchor: pos: " << Anchor_[i].pos_
+                       << " idx: " << Anchor_[i].idx_
+                       << " par: " << Anchor_[i].par_ << "\n";
+
+       lyxerr  << " sel: " << selection_ << "\n";
+}
 
-       clearLastCode();
 
-       if (sel && !selection)
-               SelStart();
+void MathCursor::seldump(char const * str) const
+{
+       //lyxerr << "SEL: " << str << ": '" << theSelection << "'\n";
+       //dump("   Pos");
+
+       lyxerr << "\n\n\n=================vvvvvvvvvvvvv=======================   "
+               <<  str << "\ntheSelection: " << selection_
+               << " '" << theSelection.glue() << "'\n";
+       for (unsigned int i = 0; i < Cursor_.size(); ++i) 
+               lyxerr << Cursor_[i].par_ << "\n'" << Cursor_[i].cell() << "'\n";
+       lyxerr << "\n";
+       for (unsigned int i = 0; i < Anchor_.size(); ++i) 
+               lyxerr << Anchor_[i].par_ << "\n'" << Anchor_[i].cell() << "'\n";
+       //lyxerr << "\ncursor.pos_: " << pos();
+       //lyxerr << "\nanchor.pos_: " << anchor().pos_;
+       lyxerr << "\n===================^^^^^^^^^^^^=====================\n\n\n";
+}
+
+#else
 
-       if (!sel && selection)
-               SelClear();
+void MathCursor::seldump(char const *) const {}
+void MathCursor::dump(char const *) const {}
 
-       bool result = cursor->Prev();
+#endif
 
-       if (!result && !mathstk.Empty()) {
-               cursor = mathstk.pop();
-               cursor->Adjust();
-               result = true;
-               if (selection)
-                       SelClear();
-       } else if (result && cursor->IsActive()) {
-               if (cursor->IsScript()) {
-                       cursor->Prev();
-                       if (!cursor->IsScript())
-                               cursor->Next();
-                       cursor->Adjust();
+
+bool MathCursor::isInside(MathInset const * p) const
+{
+       for (unsigned i = 0; i < Cursor_.size(); ++i) 
+               if (Cursor_[i].par_->nucleus() == p) 
                        return true;
-               }
+       return false;
+}
 
-               if (!selection) {
-                       MathParInset * p = cursor->GetActiveInset();
-                       if (!p)
-                               return result;
 
-                       p->setArgumentIdx(p->getMaxArgumentIdx());
-                       cursor = mathstk.push();
-                       cursor->SetData(p);
-                       cursor->GoLast();
-               }
+bool MathCursor::openable(MathAtom const & t, bool sel) const
+{
+       if (!t->isActive())
+               return false;
+
+       if (t->asScriptInset())
+               return false;
+
+       if (sel) {
+               // we can't move into anything new during selection
+               if (Cursor_.size() == Anchor_.size())
+                       return false;
+               if (&t != Anchor_[Cursor_.size()].par_)
+                       return false;
        }
-       return result;
+       return true;
 }
 
 
-// Leave the inset
-bool MathedCursor::Pop()
+bool MathCursor::positionable(MathAtom const & t, int x, int y) const
 {
-       if (!mathstk.Empty()) {
-               cursor = mathstk.pop();
-               cursor->Next();
-               return true;
+       if (selection_) {
+               // we can't move into anything new during selection
+               if (Cursor_.size() == Anchor_.size())
+                       return 0;
+               //if (t != Anchor_[Cursor_.size()].par_)
+               //      return 0;
        }
-       return false;
+
+       return t->nargs() && t->covers(x, y);
 }
 
 
-// Go to the inset
-bool MathedCursor::Push()
+bool MathCursor::posLeft()
 {
-       if (cursor->IsActive()) {
-               MathParInset * p = cursor->GetActiveInset();
-               if (!p)
-                       return false;
-               cursor = mathstk.push();
-               cursor->SetData(p);
-               return true;
-       }
-       return false;
+       if (pos() == 0)
+               return false;
+
+       --pos();
+
+       return true;
 }
 
 
-bool MathedCursor::Right(bool sel)
+bool MathCursor::posRight()
 {
-       if (macro_mode) {
-               MacroModeClose();
-               return true;
-       }
+       if (pos() == size())
+               return false;
 
-       clearLastCode();
+       ++pos();
 
-       if (sel && !selection)
-               SelStart();
+       return true;
+}
 
-       if (!sel && selection)
-               SelClear();
 
-       bool result = false;
+bool MathCursor::left(bool sel)
+{
+       dump("Left 1");
+       if (inMacroMode()) {
+               macroModeClose();
+               lastcode_ = LM_TC_VAR;
+               return true;
+       }
+       selHandle(sel);
+       lastcode_ = LM_TC_VAR;
 
-       if (cursor->IsActive()) {
-               if (cursor->IsScript()) {
-                       cursor->Next();
-                       // A script may be followed by another script
-                       if (cursor->IsScript())
-                               cursor->Next();
-                       return true;
-               }
+       if (hasPrevAtom() && openable(prevAtom(), sel)) {
+               pushRight(prevAtom());
+               return true;
+       } 
+       
+       return posLeft() || idxLeft() || popLeft();
+}
 
-               if (!selection) {
-                       MathParInset *p = cursor->GetActiveInset();
-                       if (!p) {
-                       lyxerr << "Math error: Inset expected." << endl;
-                       return cursor->Next();
-                       }
-                       p->setArgumentIdx(0);
-                       cursor = mathstk.push();
-                       cursor->SetData(p);
-                       result = true;
-               } else
-                       result = cursor->Next();
 
-       } else {
-               if (cursor->GetChar()!= LM_TC_CR)
-               result = cursor->Next();
-               if (!result && !mathstk.Empty()) {
-                       cursor = mathstk.pop();
-                       cursor->Next();
-                       cursor->Adjust();
-                       result = true;
-                       if (selection)
-                               SelClear();
-               }
+bool MathCursor::right(bool sel)
+{
+       dump("Right 1");
+       if (inMacroMode()) {
+               macroModeClose();
+               lastcode_ = LM_TC_VAR;
+               return true;
        }
-       return result;
+       selHandle(sel);
+       lastcode_ = LM_TC_VAR;
+
+       if (hasNextAtom() && openable(nextAtom(), sel)) {
+               pushLeft(nextAtom());
+               return true;
+       }
+
+       return posRight() || idxRight() || popRight();
 }
 
 
-void MathedCursor::SetPos(int x, int y)
+void MathCursor::first()
 {
-       int xp = 0;
+       Cursor_.clear();
+       pushLeft(formula_->par());
+}
 
-       if (macro_mode)
-               MacroModeClose();
 
-       lastcode = LM_TC_MIN;
-       mathstk.Reset();
-       cursor = mathstk.push();
-       cursor->SetData(par);
-       cursor->fitCoord(x, y);
+void MathCursor::last()
+{
+       first();
+       end();
+}
+
 
-       while (cursor->GetX()<x && cursor->OK()) {
-               if (cursor->IsActive()) {
-                       MathParInset * p = cursor->GetActiveInset();
-                       if (p->Inside(x, y)) {
-                               p->SetFocus(x, y);
-                               cursor = mathstk.push();
-                               cursor->SetData(p);
-                               cursor->fitCoord(x, y);
-                               continue;
+void MathCursor::setPos(int x, int y)
+{
+       //dump("setPos 1");
+       //lyxerr << "MathCursor::setPos x: " << x << " y: " << y << "\n";
+
+       macroModeClose();
+       lastcode_ = LM_TC_VAR;
+       first();
+
+       cursor().par_  = &formula_->par();
+
+       while (1) {
+               idx() = 0;
+               cursor().pos_ = 0;
+               //lyxerr << "found idx: " << idx() << " cursor: " << pos()  << "\n";
+               int distmin = 1 << 30; // large enough
+               for (unsigned int i = 0; i < par()->nargs(); ++i) {
+                       MathXArray const & ar = par()->xcell(i);
+                       int x1 = x - ar.xo();
+                       int y1 = y - ar.yo();
+                       MathXArray::size_type c  = ar.x2pos(x1);
+                       int xx = abs(x1 - ar.pos2x(c));
+                       int yy = abs(y1);
+                       //lyxerr << "idx: " << i << " xx: " << xx << " yy: " << yy
+                       //      << " c: " << c  << " xo: " << ar.xo() << "\n";
+                       if (yy + xx <= distmin) {
+                               distmin = yy + xx;
+                               idx()   = i;
+                               pos()   = c;
                        }
                }
-               xp = cursor->GetX();
-               cursor->ipush();
-               if (!cursor->Next() && !Pop())
+               //lyxerr << "found idx: " << idx() << " cursor: "
+               //      << pos()  << "\n";
+               if (hasNextAtom() && positionable(nextAtom(), x, y))
+                       pushLeft(nextAtom());
+               else if (hasPrevAtom() && positionable(prevAtom(), x, y))
+                       pushRight(prevAtom());
+               else 
                        break;
        }
-       if (x - xp < cursor->GetX() - x)
-               cursor->ipop();
-       cursor->Adjust();
+       //dump("setPos 2");
 }
 
 
-void MathedCursor::Home()
+void MathCursor::home(bool sel)
 {
-       if (macro_mode)
-               MacroModeClose();
-       clearLastCode();
-       mathstk.Reset();
-       cursor = mathstk.push();
-       cursor->GoBegin();
+       dump("home 1");
+       selHandle(sel);
+       macroModeClose();
+       lastcode_ = LM_TC_VAR;
+       if (!par()->idxHome(idx(), pos())) 
+               popLeft();
+       dump("home 2");
 }
 
 
-void MathedCursor::End()
+void MathCursor::end(bool sel)
 {
-       if (macro_mode)
-               MacroModeClose();
-       clearLastCode();
-       mathstk.Reset();
-       cursor = mathstk.push();
-       cursor->GoLast();
+       dump("end 1");
+       selHandle(sel);
+       macroModeClose();
+       lastcode_ = LM_TC_VAR;
+       if (!par()->idxEnd(idx(), pos()))
+               popRight();
+       dump("end 2");
 }
 
 
-MathMatrixInset * create_multiline(short int type, int cols)
+void MathCursor::plainErase()
 {
-       int columns;
-       string align;
-       if (cols < 1)
-               cols = 1;
+       array().erase(pos());
+}
 
-       switch (type) {
-               case LM_OT_ALIGN:
-               case LM_OT_ALIGNN:
-                       columns = 2*cols;
-                       for (int i = 0; i < cols; ++i)
-                       align += "Rl";
-                       break;
 
-               case LM_OT_ALIGNAT:
-               case LM_OT_ALIGNATN:
-                       columns = 2*cols;
-                       for (int i = 0; i < cols; ++i)
-                       align += "rl";
-                       break;
+void MathCursor::plainInsert(MathAtom const & t)
+{
+       array().insert(pos(), t);
+       ++pos();
+}
 
-               case LM_OT_MULTLINE:
-               case LM_OT_MULTLINEN:
-                       columns = 1;
-                       align = "C";
-                       break;
 
-               case LM_OT_MPAR:
-               case LM_OT_MPARN:
-               default:
-                       columns = 3;
-                       align = "rcl";
-                       break;
+void MathCursor::insert(char c, MathTextCodes t)
+{
+       //lyxerr << "inserting '" << c << "'\n";
+       plainInsert(MathAtom(new MathCharInset(c, t)));
+}
+
+
+void MathCursor::insert(MathAtom const & t)
+{
+       macroModeClose();
+
+       if (selection_) {
+               if (t->nargs())
+                       selCut();
+               else
+                       selDel();
        }
 
-       MathMatrixInset * mt = new MathMatrixInset(columns, -1);
-       mt->SetAlign(' ', align);
-       return mt;
-}
-
-
-void MathedCursor::Insert(byte c, MathedTextCodes t)
-{
-       if (selection)
-               SelDel();
-
-       if (t == LM_TC_MIN)
-               t = lastcode;
-
-       if (macro_mode && !(MathIsAlphaFont(t) || t == LM_TC_MIN))
-               MacroModeClose();
-
-       if (t == LM_TC_CR) {
-               MathParInset * p = cursor->getPar();
-               if (p == par && p->GetType()<LM_OT_MPAR && p->GetType()>LM_OT_MIN) {
-                       short int type = LM_OT_MPAR;
-                       int cols = 1;
-                       if (c >= '1' && c <= '9') {
-                               type = LM_OT_ALIGN;
-                               cols = c - '1' + 1;
-                       } else if (c >= 'A' && c <= 'I') {
-                               type = LM_OT_ALIGNAT;
-                               cols = c - 'A' + 1;
-                       } else if (c == 'm')
-                               type = LM_OT_MULTLINE;
-                       else if (c == 'e')
-                               type = LM_OT_MPAR;
-
-                       if (p->GetType() == LM_OT_PARN)
-                               ++type;
-                       MathMatrixInset * mt = create_multiline(type, cols);
-                       mt->SetStyle(LM_ST_DISPLAY);
-                       mt->SetType(type);
-                       mt->setData(p->GetData());
-                       delete p;
-                       par = mt;
-                       p = mt;
-                       p->Metrics();
-                       int pos = cursor->getPos();
-                       cursor->SetData(par);
-                       cursor->goPosAbs(pos);
-               }
-               if (p &&  p->Permit(LMPF_ALLOW_CR)) {
-                       cursor->addRow();
-               }
-       } else if (t == LM_TC_TAB) {
-               MathParInset * p = cursor->getPar();
-               if (p &&  p->Permit(LMPF_ALLOW_TAB)) {
-                       if (c) {
-                               cursor->insert(c, t);
-                               cursor->checkTabs();
-                       } else
-                               cursor->goNextColumn();
-               } else // Navigate between arguments
-               if (p && p->GetType() == LM_OT_MACRO) {
-                       if (p->getArgumentIdx() < p->getMaxArgumentIdx()) {
-                               p->setArgumentIdx(p->getArgumentIdx() + 1);
-                               cursor->SetData(p);
-                               return;
-                       }
-               }
-       } else {
-               if (macro_mode) {
-                       if (MathIsAlphaFont(t) || t == LM_TC_MIN) {
-                               // was MacroModeInsert(c);
-                               imacro->SetName(imacro->GetName() + static_cast<char>(c));
-                               return;
-                       }
-               }
+       plainInsert(t);
+}
 
-               if (accent) {
-                       doAccent(c, t);
-               } else
-                       cursor->insert(c, t);
 
-               lastcode = t;
-               return;
+void MathCursor::niceInsert(MathAtom const & t) 
+{
+       selCut();
+       insert(t); // inserting invalidates the pointer!
+       MathAtom const & p = prevAtom();
+       if (p->nargs()) {
+               posLeft();
+               right();  // do not push for e.g. MathSymbolInset
+               selPaste();
        }
-       clearLastCode();
+       p->metrics(p->size());
 }
 
 
-void MathedCursor::insertInset(MathedInset * p, int t)
+void MathCursor::insert(MathArray const & ar)
 {
-       if (macro_mode)
-               MacroModeClose();
+       macroModeClose();
+       if (selection_)
+               selCut();
 
-       if (selection) {
-               if (MathIsActive(t)) {
-                       SelCut();
-                       static_cast<MathParInset*>(p)->setData(selarray);
-               } else
-                       SelDel();
-       }
+       array().insert(pos(), ar);
+       pos() += ar.size();
+}
 
-       if (mathstk.i < MAX_STACK_ITEMS - 1) {
-               if (accent && !MathIsActive(t)) {       
-                       doAccent(p);
-               } else {
-                       cursor->insertInset(p, t);
-                       if (MathIsActive(t)) {
-                               cursor->Prev();
-                               Push();
-                       }
-               }
-       } else
-               lyxerr << "Math error: Full stack." << endl;
+
+void MathCursor::paste(MathArray const & ar)
+{
+       Anchor_ = Cursor_;
+       selection_ = true;
+       array().insert(pos(), ar);
+       pos() += ar.size();
 }
 
 
-void MathedCursor::Delete()
+void MathCursor::backspace()
 {
-       if (macro_mode)
+       if (pos() == 0) {
+               pullArg(false);
                return;
+       }       
 
-       if (selection) {
-               SelDel();
+       if (selection_) {
+               selDel();
                return;
        }
 
-       if (cursor->Empty() && !mathstk.Empty()) 
-               cursor = mathstk.pop();
+       MathScriptInset * p = prevAtom()->asScriptInset();
+       if (p) {
+               p->removeScript(p->hasUp());
+               // Don't delete if there is anything left 
+               if (p->hasUp() || p->hasDown())
+                       return;
+       }
 
-       //   if (cursor->GetChar()!= LM_TC_TAB)
-       cursor->Delete();
-       cursor->checkTabs();
+       --pos();
+       plainErase();
 }
 
 
-void MathedCursor::DelLine()
+void MathCursor::erase()
 {
-       if (macro_mode)
-               MacroModeClose();
+       if (inMacroMode())
+               return;
+
+       if (selection_) {
+               selDel();
+               return;
+       }
 
-       if (selection) {
-               SelDel();
+       // delete empty cells if necessary
+       if (array().empty()) {
+               bool popit;
+               bool removeit;
+               par()->idxDelete(idx(), popit, removeit);
+               if (popit && popLeft() && removeit)
+                       plainErase();
                return;
        }
 
-       MathParInset * p = cursor->getPar();
+       if (pos() == size())
+               return;
 
-       if (p && p->GetType() <= LM_OT_MATRIX && p->GetType() >= LM_OT_MPAR) {
-               cursor->delRow();
+       MathScriptInset * p = nextAtom()->asScriptInset();
+       if (p) {
+               p->removeScript(p->hasUp());
+               // Don't delete if there is anything left 
+               if (p->hasUp() || p->hasDown())
+                       return;
        }
+
+       plainErase();
 }
 
 
-bool MathedCursor::Up(bool sel)
+void MathCursor::delLine()
 {
-       bool result = false;
+       macroModeClose();
 
-       if (macro_mode)
-               MacroModeClose();
+       if (selection_) {
+               selDel();
+               return;
+       }
 
-       if (sel && !selection)
-               SelStart();
+       if (par()->nrows() > 1)
+               par()->delRow(row());
+}
 
-       if (!sel && selection)
-               SelClear();
 
-       if (cursor->IsScript()) {
-               char cd = cursor->GetChar();
-               if (MathIsUp(cd)) {
-                       Push();
-                       return true;
-               } else {
-                       // A subscript may be followed by a superscript
-                       cursor->ipush();
-                       cursor->Next();
-                       if (MathIsUp(cursor->GetChar())) {
-                               Push();
+bool MathCursor::up(bool sel)
+{
+       dump("up 1");
+       macroModeClose();
+       selHandle(sel);
+
+       if (!selection_) {
+               // check whether we could move into a superscript 
+               if (hasPrevAtom()) {
+                       MathAtom & p = prevAtom();
+                       if (p->asScriptInset() && p->asScriptInset()->hasUp()) {
+                               pushRight(p);
+                               idx() = 1;
+                               pos() = size();
                                return true;
-                       } else  // return to the previous state
-                               cursor->ipop();
+                       }
+               }
+
+               if (hasNextAtom()) {
+                       MathAtom & n = nextAtom();
+                       if (n->asScriptInset() && n->asScriptInset()->hasUp()) {
+                               pushLeft(n);
+                               idx() = 1;
+                               pos() = 0;
+                               return true;
+                       }
                }
        }
 
-       result = cursor->Up();
-       if (!result && cursor->getPar()) {
-               MathParInset * p = cursor->getPar();
+       return goUp();
+}
 
-               if (p->GetType() == LM_OT_SCRIPT) {
-                       MathedXIter * cx = mathstk.Item(1);
-                       bool is_down = (cx->GetChar() == LM_TC_DOWN);
-                       cursor = mathstk.pop();
-                       cursor->Next();
-                       result =  (is_down) ? true: Up();
-               } else {
-                       result = (p->getArgumentIdx() > 0);
-                       if (result) {
-                               p->setArgumentIdx(p->getArgumentIdx() - 1);
-                               cursor->SetData(p);
+
+bool MathCursor::down(bool sel)
+{
+       dump("down 1");
+       macroModeClose();
+       selHandle(sel);
+
+       if (!selection_) {
+               // check whether we could move into a subscript 
+               if (hasPrevAtom()) {
+                       MathAtom & p = prevAtom();
+                       if (p->asScriptInset() && p->asScriptInset()->hasDown()) {
+                               pushRight(p);
+                               idx() = 0;
+                               pos() = size();
+                               return true;
                        }
                }
 
-               if (!result && !mathstk.Empty()) {
-                       cursor = mathstk.pop();
-                       return Up();
+               if (hasNextAtom()) {
+                       MathAtom & n = nextAtom();
+                       if (n->asScriptInset() && n->asScriptInset()->hasDown()) {
+                               pushLeft(n);
+                               idx() = 0;
+                               pos() = 0;
+                               return true;
+                       }
                }
        }
-       return result;
+
+       return goDown();
 }
 
 
-bool MathedCursor::Down(bool sel)
+bool MathCursor::toggleLimits()
 {
-       bool result = false;
+       if (!hasPrevAtom())
+               return false;
+       MathScriptInset * t = prevAtom()->asScriptInset();
+       if (!t)
+               return false;
+       int old = t->limits();
+       t->limits(old < 0 ? 1 : -1);
+       return old != t->limits();
+}
 
-       if (macro_mode)
-               MacroModeClose();
 
-       if (sel && !selection)
-               SelStart();
+void MathCursor::setSize(MathStyles size)
+{
+       par()->userSetSize(size);
+}
 
-       if (!sel && selection)
-               SelClear();
 
-       if (cursor->IsScript()) {
-               char cd = cursor->GetChar();
-               if (MathIsDown(cd)) {
-                       Push();
-                       return true;
-               } else {
-               // A superscript may be followed by a subscript
-               cursor->ipush();
-               cursor->Next();
-               if (MathIsDown(cursor->GetChar())) {
-                       Push();
-                       return true;
-               } else
-                       cursor->ipop();
-               }
+void MathCursor::macroModeClose()
+{
+       string s = macroName();
+       if (s.size()) {
+               size_type old = pos();
+               pos() -= s.size();
+               array().erase(pos(), old);
+               interpret(s);
        }
+}
 
-       result = cursor->Down();
-       if (!result && cursor->getPar()) {
-               MathParInset * p= cursor->getPar();
-               if (p->GetType() == LM_OT_SCRIPT) {
-                       MathedXIter * cx = mathstk.Item(1);
-                       bool is_up = (cx->GetChar() == LM_TC_UP);
-                       cursor = mathstk.pop();
-                       cursor->Next();
-                       result = (is_up) ? true : Down();
-               } else {
-                       result = (p->getArgumentIdx() < p->getMaxArgumentIdx());
-                       if (result) {
-                               p->setArgumentIdx(p->getArgumentIdx() + 1);
-                               cursor->SetData(p);
-                       }
-               }
-               if (!result && !mathstk.Empty()) {
-                       cursor = mathstk.pop();
-                       return Down(sel);
-               }
+
+int MathCursor::macroNamePos() const
+{
+       for (int i = pos() - 1; i >= 0; --i) { 
+               MathAtom & p = array().at(i);
+               if (p->code() == LM_TC_TEX && p->getChar() == '\\')
+                       return i;
        }
-       return result;
+       return -1;
 }
 
 
-bool MathedCursor::Limits()
+string MathCursor::macroName() const
 {
-       if (cursor->IsInset()) {
-               MathedInset * p = cursor->GetInset();
-               bool ol = p->GetLimits();
-               p->SetLimits(!ol);
-               return (ol!= p->GetLimits());
+       string s;
+       for (int i = macroNamePos(); i >= 0 && i < int(pos()); ++i) 
+               s += array().at(i)->getChar();
+       return s;
+}
+
+
+void MathCursor::selCopy()
+{
+       seldump("selCopy");
+       if (selection_) {
+               theSelection.grab(*this);
+               selClear();
        }
-       return false;
 }
 
 
-void MathedCursor::SetSize(short size)
+void MathCursor::selCut()
 {
-       MathParInset * p = cursor->getPar();
-       p->UserSetSize(size);
-       cursor->SetData(p);
+       seldump("selCut");
+       if (selection_) {
+               theSelection.grab(*this);
+               theSelection.erase(*this);
+               selClear();
+       } else {
+               theSelection.clear();
+       }
 }
 
 
-void MathedCursor::setLabel(string const & label)
+void MathCursor::selDel()
 {
-       // ugly hack and possible bug
-       if (!cursor->setLabel(label))
-               lyxerr << "MathErr: Bad place to set labels." << endl;
+       seldump("selDel");
+       if (selection_) {
+               theSelection.erase(*this);
+               selClear();
+       }
 }
 
 
-void MathedCursor::setNumbered()
+void MathCursor::selPaste()
 {
-       // another ugly hack
-       MathedRowContainer::iterator crow = cursor->currentRow();
-       if (crow)
-               crow->setNumbered(!crow->isNumbered());
+       seldump("selPaste");
+       theSelection.paste(*this);
+       theSelection.grab(*this);
+       //selClear();
 }
 
 
-void MathedCursor::Interpret(string const & s)
+void MathCursor::selHandle(bool sel)
 {
-       MathedInset * p = 0;
-       latexkeys const * l = 0;
-       MathedTextCodes tcode = LM_TC_INSET;
+       if (sel == selection_)
+               return;
 
-       if (s[0] == '^' || s[0] == '_') {
-               char c = cursor->GetChar();
-               if (MathIsUp(c) && s[0] == '^' || MathIsDown(c) && s[0] == '_') {
-                       Push();
-                       return;
-               } else
-
-               // A script may be followed by a script
-               if (MathIsUp(c)  || MathIsDown(c)) {
-                       cursor->ipush();
-                       cursor->Next();
-                       c = cursor->GetChar();
-                       if (MathIsUp(c) && s[0] == '^' || MathIsDown(c) && s[0] == '_') {
-                               Push();
-                               return;
-                       } else
-                               cursor->ipop();
-               }
-               p = new MathParInset(LM_ST_SCRIPT, "", LM_OT_SCRIPT);
-               insertInset(p, (s[0] == '_') ? LM_TC_DOWN: LM_TC_UP);
+       theSelection.clear();
+       Anchor_    = Cursor_;
+       selection_ = sel;
+}
+
+
+void MathCursor::selStart()
+{
+       seldump("selStart");
+       if (selection_)
                return;
-       } else
-       if (s[0] == '!' || s[0] == ','  || s[0] == ':' || s[0] == ';') {
-               int sp = ((s[0] == ',') ? 1:((s[0] == ':') ? 2:((s[0] == ';') ? 3: 0)));
-               p = new MathSpaceInset(sp);
-               insertInset(p, LM_TC_INSET);
+
+       theSelection.clear();
+       Anchor_ = Cursor_;
+       selection_ = true;
+}
+
+
+void MathCursor::selClear()
+{
+       seldump("selClear");
+       selection_ = false;
+}
+
+
+void MathCursor::drawSelection(Painter & pain) const
+{
+       if (!selection_)
                return;
-       } else
-               l = in_word_set(s);
-
-       if (!l) {
-               p = MathMacroTable::mathMTable.createMacro(s);
-               if (!p) {
-               lyxerr[Debug::MATHED] << "Macro2 " << s << ' ' << tcode << endl;
-               if (s == "root") {
-                       p = new MathRootInset;
-                       tcode = LM_TC_ACTIVE_INSET;
-               } else
-                       p = new MathFuncInset(s, LM_OT_UNDEF);
-               } else {
-                       tcode = static_cast<MathMacro*>(p)->getTCode();
-                       lyxerr[Debug::MATHED] << "Macro2 " << s << ' ' << tcode << endl;
-               }
+
+       MathCursorPos i1;
+       MathCursorPos i2;
+       getSelection(i1, i2);
+
+       //lyxerr << "selection from: " << i1 << " to " << i2 << "\n";
+
+       if (i1.idx_ == i2.idx_) {
+               MathXArray & c = i1.xcell();
+               int x1 = c.xo() + c.pos2x(i1.pos_);
+               int y1 = c.yo() - c.ascent();
+               int x2 = c.xo() + c.pos2x(i2.pos_);
+               int y2 = c.yo() + c.descent();
+               pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
        } else {
-               MathedInsetTypes fractype = LM_OT_FRAC;
-               switch (l->token) {
-                       case LM_TK_BIGSYM: 
-                                       p = new MathBigopInset(l->name, l->id);
-                                       break;
-                               
-                       case LM_TK_SYM: 
-                                       if (l->id<255) {
-                                               Insert(static_cast<byte>(l->id), MathIsBOPS(l->id) ?
-                                               LM_TC_BOPS: LM_TC_SYMB);        
-                                       } else {
-                                               p = new MathFuncInset(l->name);
-                                       }
-                                       break;
-                               
-                       case LM_TK_STACK:
-                               fractype = LM_OT_STACKREL;
-                               lyxerr[Debug::MATHED] << " i:stackrel " << endl;
-
-                       case LM_TK_FRAC:
-                               p = new MathFracInset(fractype);
-                               tcode = LM_TC_ACTIVE_INSET;
-                               break;
-
-                       case LM_TK_SQRT:
-                               p = new MathSqrtInset;
-                               tcode = LM_TC_ACTIVE_INSET;
-                               break;
-
-                       case LM_TK_WIDE:
-                               p = new MathDecorationInset(l->id);
-                               tcode = LM_TC_ACTIVE_INSET;
-                               break;
-
-                       case  LM_TK_FUNCLIM:
-                               p = new MathFuncInset(l->name, LM_OT_FUNCLIM);
-                               break;
-
-                       case LM_TK_SPACE:
-                               p = new MathSpaceInset(l->id);
-                               break;
-
-                       case LM_TK_DOTS:
-                               p = new MathDotsInset(l->name, l->id);
-                               break;
-
-                       case LM_TK_ACCENT:
-                               setAccent(l->id);
-                               break;
-
-                       case LM_TK_MACRO:
-                               p = MathMacroTable::mathMTable.createMacro(s);
-                               tcode = static_cast<MathMacro*>(p)->getTCode();
-                               lyxerr[Debug::MATHED] << "Macro " << s << ' ' << tcode << endl;
-                               break;
-
-                       default:
-                               p = new MathFuncInset(l->name);
-                               break;
+               std::vector<MathInset::idx_type> indices
+                       = (*i1.par_)->idxBetween(i1.idx_, i2.idx_);
+               for (unsigned i = 0; i < indices.size(); ++i) {
+                       MathXArray & c = i1.xcell(indices[i]);
+                       int x1 = c.xo();
+                       int y1 = c.yo() - c.ascent();
+                       int x2 = c.xo() + c.width();
+                       int y2 = c.yo() + c.descent();
+                       pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
                }
        }
-
-       if (p) {
-               insertInset(p, tcode);
-               par->Metrics();
-       }
 }
 
 
-bool MathedCursor::pullArg()
+void MathCursor::handleFont(MathTextCodes t)
 {
-       if (cursor->IsActive()) {
-               MathParInset * p = cursor->GetActiveInset();
-               if (!p) 
-                       return false;
-               
-               MathedArray a = p->GetData();
-               p->clear();
-               Delete();
-               if (!a.empty()) {
-                       cursor->Merge(a);
-                       cursor->Adjust();
+       macroModeClose();
+       if (selection_) {
+               MathCursorPos i1;
+               MathCursorPos i2;
+               getSelection(i1, i2); 
+               if (i1.idx_ == i2.idx_) {
+                       MathArray & ar = i1.cell();
+                       for (MathInset::pos_type pos = i1.pos_; pos != i2.pos_; ++pos)
+                               ar.at(pos)->handleFont(t);
                }
+       } else 
+               lastcode_ = (lastcode_ == t) ? LM_TC_VAR : t;
+}
 
-               return true;
+
+void MathCursor::handleDelim(string const & l, string const & r)
+{
+       handleNest(new MathDelimInset(l, r));
+}
+
+
+void MathCursor::handleNest(MathInset * p)
+{
+       if (selection_) {
+               selCut();
+               p->cell(0) = theSelection.glue();
        }
-       return false;
+       insert(MathAtom(p)); // this invalidates p!
+       pushRight(prevAtom());
 }
 
 
-void MathedCursor::MacroModeOpen()
+void MathCursor::getPos(int & x, int & y)
 {
-       if (!macro_mode) {
-               imacro = new MathFuncInset("");
-               insertInset(imacro, LM_TC_INSET);
-               macro_mode = true;
-       } else
-               lyxerr << "Mathed Warning: Already in macro mode" << endl;
+#ifdef WITH_WARNINGS
+#warning This should probably take cellXOffset and cellYOffset into account
+#endif
+       x = xarray().xo() + xarray().pos2x(pos());
+       y = xarray().yo();
 }
 
 
-void MathedCursor::MacroModeClose()
+MathAtom & MathCursor::par() const
 {
-       if (macro_mode)  {
-               macro_mode = false;
-               latexkeys const * l = in_word_set(imacro->GetName());
-               if (!imacro->GetName().empty()
-               && (!l || (l && IsMacro(l->token, l->id))) &&
-               !MathMacroTable::mathMTable.createMacro(imacro->GetName())) {
-                       if (!l) {
-                               //imacro->SetName(macrobf);
-                               // This guarantees that the string will be removed by destructor
-                               imacro->SetType(LM_OT_UNDEF);
-                       } else
-                               imacro->SetName(l->name);
-               } else {
-                       Left();
-                       if (cursor->GetInset()->GetType() == LM_OT_ACCENT) {
-                               setAccent(
-                                       static_cast<MathAccentInset*>(cursor->GetInset())->getAccentCode());
-                       }
-                       cursor->Delete();
-                       if (l || MathMacroTable::mathMTable.createMacro(imacro->GetName())) {
-                               Interpret(imacro->GetName());
-                       }
-                       imacro->SetName("");
+       return *cursor().par_;
+}
+
+
+InsetFormulaBase const * MathCursor::formula()
+{
+       return formula_;
+}
+
+
+MathCursor::idx_type MathCursor::idx() const
+{
+       return cursor().idx_;
+}
+
+
+MathCursor::idx_type & MathCursor::idx()
+{
+       return cursor().idx_;
+}
+
+
+MathCursor::pos_type MathCursor::pos() const
+{
+       return cursor().pos_;
+}
+
+
+MathCursor::pos_type & MathCursor::pos()
+{
+       return cursor().pos_;
+}
+
+
+bool MathCursor::inMacroMode() const
+{
+       return macroNamePos() != -1;
+}
+
+
+bool MathCursor::selection() const
+{
+       return selection_;
+}
+
+
+MathArrayInset * MathCursor::enclosingArray(MathCursor::idx_type & idx) const
+{
+       for (int i = Cursor_.size() - 1; i >= 0; --i) {
+               MathArrayInset * p = (*Cursor_[i].par_)->asArrayInset();
+               if (p) {
+                       idx = Cursor_[i].idx_;
+                       return p;
                }
-               imacro = 0;
        }
+       return 0;
 }
 
 
-void MathedCursor::SelCopy()
+void MathCursor::pullArg(bool goright)
 {
-       if (selection) {
-               int const p1 = (cursor->getPos() < selpos) ?
-                       cursor->getPos() : selpos;
-               int const p2 = (cursor->getPos() > selpos) ?
-                       cursor->getPos() : selpos;
-               selarray = *(cursor->GetData());
-               selarray.shrink(p1, p2);
-               cursor->Adjust();
-               SelClear();
+       dump("pullarg");
+       MathArray a = array();
+
+       MathScriptInset const * p = par()->asScriptInset();
+       if (p) {
+               // special handling for scripts
+               const bool up = p->hasUp();
+               popLeft();
+               MathScriptInset * q = nextAtom()->asScriptInset();
+               if (q)
+                       q->removeScript(up);
+               ++pos();
+               array().insert(pos(), a);
+               return;
+       }
+
+       if (popLeft()) {
+               plainErase();
+               array().insert(pos(), a);
+               if (goright) 
+                       pos() += a.size();
        }
 }
 
 
-void MathedCursor::SelCut()
+MathStyles MathCursor::style() const
 {
-       if (selection) {
-               if (cursor->getPos() == selpos)
-                       return;
+       return xarray().style();
+}
 
-               int const p1 = (cursor->getPos() < selpos) ?
-                       cursor->getPos() : selpos;
-               int const p2 = (cursor->getPos() > selpos) ?
-                       cursor->getPos() : selpos;
-               selarray = *(cursor->GetData());
-               selarray.shrink(p1, p2);
-               cursor->Clean(selpos);
-               cursor->Adjust();
-               SelClear();
+
+void MathCursor::normalize() const
+{
+#ifdef WITH_WARNINGS
+#warning This is evil!
+#endif
+       MathCursor * it = const_cast<MathCursor *>(this);
+
+       if (idx() >= par()->nargs()) {
+               lyxerr << "this should not really happen - 1: "
+                      << idx() << " " << par()->nargs() << "\n";
+               dump("error 2");
+       }
+       it->idx()    = min(idx(), par()->nargs() - 1);
+
+       if (pos() > size()) {
+               lyxerr << "this should not really happen - 2: "
+                      << pos() << " " << size() << "\n";
+               dump("error 4");
        }
+       it->pos() = min(pos(), size());
 }
 
 
-void MathedCursor::SelDel()
+MathCursor::size_type MathCursor::size() const
 {
-       //  lyxerr << "Deleting sel "
-       if (selection) {
-               if (cursor->getPos() == selpos)
-                       return;
-               cursor->Clean(selpos);
-               cursor->Adjust();
-               SelClear();
-       }
+       return array().size();
 }
 
 
-void MathedCursor::SelPaste()
+MathCursor::col_type MathCursor::col() const
 {
-       // lyxerr << "paste " << selarray << " " << curor->pos;
-       if (selection)
-               SelDel();
+       return par()->col(idx());
+}
 
-       if (!selarray.empty()) {
-               cursor->Merge(selarray);
-               cursor->Adjust();
-       }
+
+MathCursor::row_type MathCursor::row() const
+{
+       return par()->row(idx());
 }
 
 
-void MathedCursor::SelStart()
+bool MathCursor::hasPrevAtom() const
 {
-       lyxerr[Debug::MATHED] << "Starting sel " << endl;
-       if (!anchor) {
-               selpos = cursor->getPos();
-               selstk = mathstk;
-               anchor = selstk.Item(-1);
-               anchor->SetData(cursor->getPar());
-               anchor->GoBegin();
-               anchor->goPosAbs(selpos);
-               selection = true;
-       }
+       return pos() > 0;
 }
 
 
-void MathedCursor::SelClear()
+bool MathCursor::hasNextAtom() const
 {
-       lyxerr[Debug::MATHED] << "Clearing sel " << endl;
-       selection = false;
-       anchor = 0;
+       return pos() < size();
 }
 
 
+MathAtom const & MathCursor::prevAtom() const
+{
+       lyx::Assert(pos() > 0);
+       return array().at(pos() - 1);
+}
 
-// Anchor position must be at the same level that stack.
-void MathedCursor::SelBalance()
+
+MathAtom & MathCursor::prevAtom()
 {
-       int d = mathstk.Level() - selstk.Level();
+       lyx::Assert(pos() > 0);
+       return array().at(pos() - 1);
+}
 
-       // If unbalanced, balance them
-       while (d != 0) {
-               if (d < 0) {
-                       // lyxerr << "b[" << mathstk.Level() << " " << selstk.Level
-                       //  << " " << anchor->GetX() << " " << cursor->GetX() << "]";
-                       anchor = selstk.pop();
-                       if (anchor->GetX() >= cursor->GetX())
-                       anchor->Next();
-               } else {
-                       // lyxerr <<"a[" << mathstk.Level() << " " << selstk.Level() <<"]";
-                       Pop();
-               }
-               d = mathstk.Level() - selstk.Level();
+
+MathAtom const & MathCursor::nextAtom() const
+{
+       lyx::Assert(pos() < size());
+       return array().at(pos());
+}
+
+
+MathAtom & MathCursor::nextAtom()
+{
+       lyx::Assert(pos() < size());
+       return array().at(pos());
+}
+
+
+MathArray & MathCursor::array() const
+{
+       static MathArray dummy;
+
+       if (idx() >= par()->nargs()) {
+               lyxerr << "############  idx_ " << idx() << " not valid\n";
+               return dummy;
        }
 
-       // Once balanced the levels, check that they are at the same paragraph
-       selpos = anchor->getPos();
+       return cursor().cell();
+}
+
+
+MathXArray & MathCursor::xarray() const
+{
+       return cursor().xcell();
+}
+
+
+void MathCursor::idxNext()
+{
+       par()->idxNext(idx(), pos());
 }
 
 
-void MathedCursor::SelGetArea(int ** xp, int ** yp, int & np)
+void MathCursor::idxPrev()
 {
-       static int xpoint[10];
-       static int ypoint[10];
+       par()->idxPrev(idx(), pos());
+}
+
 
-       if (!selection) {
-               np = 0;
-               xpoint[0] = 0;
-               ypoint[0] = 0;
-               *xp = &xpoint[0];
-               *yp = &ypoint[0];
+void MathCursor::splitCell()
+{
+       if (idx() == par()->nargs() - 1) 
                return;
-       }
+       MathArray ar = array();
+       ar.erase(0, pos());
+       array().erase(pos(), size());
+       ++idx();
+       pos() = 0;
+       array().insert(0, ar);
+}
 
-       // Balance anchor and cursor
-       SelBalance();
-
-       int xo;
-       int yo;
-       cursor->getPar()->GetXY(xo, yo);
-       int w = cursor->getPar()->Width();
-       int x1;
-       int y1;
-       cursor->GetPos(x1, y1);
-       int a1;
-       int d1;
-       cursor->getAD(a1, d1);
-       int x;
-       int y;
-       anchor->GetPos(x, y);
-       int a;
-       int d;
-       anchor->getAD(a, d);
-
-       // single row selection
-       int i = 0;
-       xpoint[i]   = x;
-       ypoint[i++] = y + d;
-       xpoint[i]   = x;
-       ypoint[i++] = y - a;
-
-       if (y != y1) {
-               xpoint[i]   = xo + w;
-               ypoint[i++] = y - a;
-
-               if (x1 < xo + w) {
-               xpoint[i]   = xo + w;
-               ypoint[i++] = y1 - a;
-       }
-       }
 
-       xpoint[i]   = x1;
-       ypoint[i++] = y1 - a;
-       xpoint[i]   = x1;
-       ypoint[i++] = y1 + d;
-
-       if (y != y1) {
-               xpoint[i]   = xo;
-               ypoint[i++] = y1 + d;
-               if (x > xo) {
-                       xpoint[i]   = xo;
-                       ypoint[i++] = y + d;
+void MathCursor::breakLine()
+{
+       // leave inner cells
+       while (popRight())
+               ;
+
+       MathMatrixInset * p = formula()->par()->asMatrixInset();
+       if (!p)
+               return;
+
+       if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
+               p->mutate(LM_OT_EQNARRAY);
+               idx() = 0;
+               pos() = size();
+       } else {
+               p->addRow(row());
+
+               // split line
+               const row_type r = row();
+               for (col_type c = col() + 1; c < p->ncols(); ++c) {
+                       const MathMatrixInset::idx_type i1 = p->index(r, c);
+                       const MathMatrixInset::idx_type i2 = p->index(r + 1, c);        
+                       lyxerr << "swapping cells " << i1 << " and " << i2 << "\n";
+                       p->cell(i1).swap(p->cell(i2));
                }
+
+               // split cell
+               splitCell();
+               p->cell(idx()).swap(p->cell(idx() + p->ncols() - 1));
        }
-       xpoint[i]   = xpoint[0];
-       ypoint[i++] = ypoint[0];
+}
+
 
-       *xp = &xpoint[0];
-       *yp = &ypoint[0];
-       np = i;
-       //    lyxerr << "AN[" << x << " " << y << " " << x1 << " " << y1 << "] ";
-       //    lyxerr << "MT[" << a << " " << d << " " << a1 << " " << d1 << "] ";
-       //    for (i = 0; i < np; ++i)
-       //      lyxerr << "XY[" << point[i].x << " " << point[i].y << "] ";
+char MathCursor::valign() const
+{
+       idx_type idx;
+       MathArrayInset * p = enclosingArray(idx);
+       return p ? p->valign() : '\0';
 }
 
 
-void MathedCursor::setAccent(int ac)
+char MathCursor::halign() const
 {
-       if (ac > 0 && accent < 8) {
-               nestaccent[accent++] = ac;
-       } else
-               accent = 0;  // consumed!
+       idx_type idx;
+       MathArrayInset * p = enclosingArray(idx);
+       return p ? p->halign(idx % p->ncols()) : '\0';
 }
 
 
-int MathedCursor::getAccent() const
+void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
 {
-       return (accent > 0) ? nestaccent[accent - 1]: 0;
+       MathCursorPos anc = normalAnchor();
+       if (anc < cursor()) {
+               i1 = anc;
+               i2 = cursor();
+       } else {
+               i1 = cursor();
+               i2 = anc;
+       }
 }
 
 
-void MathedCursor::doAccent(byte c, MathedTextCodes t)
+MathCursorPos & MathCursor::cursor()
 {
-       MathedInset * ac = 0;
+       return Cursor_.back();
+}
+
+
+MathCursorPos const & MathCursor::cursor() const
+{
+       return Cursor_.back();
+}
+
+
+int MathCursor::cellXOffset() const
+{
+       return par()->cellXOffset(idx());
+}
+
+
+int MathCursor::cellYOffset() const
+{
+       return par()->cellYOffset(idx());
+}
+
+
+int MathCursor::xpos() const
+{
+       return cellXOffset() + xarray().pos2x(pos());
+}
+
+
+int MathCursor::ypos() const
+{
+       return cellYOffset();
+}
 
-       for (int i = accent - 1; i >= 0; --i) {
-               if (i == accent - 1)
-                       ac = new MathAccentInset(c, t, nestaccent[i]);
-               else
-                       ac = new MathAccentInset(ac, nestaccent[i]);
-       }
-       
-       if (ac)
-               cursor->insertInset(ac, LM_TC_INSET);
 
-       accent = 0;  // consumed!
+
+void MathCursor::gotoX(int x) 
+{
+       pos() = xarray().x2pos(x - cellXOffset());
 }
 
 
-void MathedCursor::doAccent(MathedInset * p)
+bool MathCursor::goUp()
 {
-       MathedInset * ac = 0;
+       // first ask the inset if it knows better then we
+       if (par()->idxUp(idx(), pos()))
+               return true;
 
-       for (int i = accent - 1; i >= 0; --i) {
-               if (i == accent - 1)
-                       ac = new MathAccentInset(p, nestaccent[i]);
+       // leave subscript to the nearest side  
+       MathScriptInset * p = par()->asScriptInset();
+       if (p && p->hasDown()) {
+               if (pos() <= size() / 2)
+                       popLeft();
                else
-                       ac = new MathAccentInset(ac, nestaccent[i]);
+                       popRight();             
+               return true;
        }
 
-       if (ac)
-               cursor->insertInset(ac, LM_TC_INSET);
-
-       accent = 0;  // consumed!
+       // if not, apply brute force.
+       int x0;
+       int y0;
+       getPos(x0, y0);
+       std::vector<MathCursorPos> save = Cursor_;
+       MathAtom const & out = formula()->par();
+       y0 -= xarray().ascent();
+       for (int y = y0 - 4; y > out->yo() - out->ascent(); y -= 4) {
+               setPos(x0, y);
+               if (save != Cursor_ && xarray().yo() < y0)
+                       return true;    
+       }
+       Cursor_ = save;
+       return false;
 }
 
 
-void MathedCursor::toggleLastCode(MathedTextCodes t)
+bool MathCursor::goDown()
 {
-       if (lastcode == t)
-               lastcode = LM_TC_VAR;
-       else
-               lastcode = t;
+       // first ask the inset if it knows better then we
+       if (par()->idxDown(idx(), pos()))
+               return true;
+
+       // leave superscript to the nearest side        
+       MathScriptInset * p = par()->asScriptInset();
+       if (p && p->hasUp()) {
+               if (pos() <= size() / 2)
+                       popLeft();
+               else
+                       popRight();             
+               return true;
+       }
+
+       // if not, apply brute force.
+       int x0;
+       int y0;
+       getPos(x0, y0);
+       std::vector<MathCursorPos> save = Cursor_;
+       MathAtom const & out = formula()->par();
+       y0 += xarray().descent();
+       for (int y = y0 + 4; y < out->yo() + out->descent(); y += 4) {
+               setPos(x0, y);
+               if (save != Cursor_ && xarray().yo() > y0)
+                       return true;    
+       }
+       Cursor_ = save;
+       return false;
 }
 
 
-void MathedCursor::GetPos(int & x, int & y)
+bool MathCursor::idxLeft()
 {
-       cursor->GetPos(x, y);
+       return par()->idxLeft(idx(), pos());
 }
 
 
-short MathedCursor::GetFCode()
+bool MathCursor::idxRight()
 {
-       return cursor->fcode();
+       return par()->idxRight(idx(), pos());
 }
 
 
-MathParInset * MathedCursor::GetPar()
+void MathCursor::interpret(string const & s)
 {
-       return par;
+       //lyxerr << "interpret 1: '" << s << "'\n";
+       //lyxerr << "in: " << in_word_set(s) << " \n";
+
+       if (s.empty())
+               return;
+
+       if (s.size() == 1) {
+               interpret(s[0]);
+               return;
+       }
+
+       //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
+       //owner_->getIntl()->getTrans().TranslateAndInsert(s[0], lt);   
+       //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
+
+       if (s.size() > 7 && s.substr(0, 7) == "matrix ") {
+               unsigned int m = 1;
+               unsigned int n = 1;
+               string v_align;
+               string h_align;
+               istringstream is(s.substr(7).c_str());
+               is >> m >> n >> v_align >> h_align;
+               m = std::max(1u, m);
+               n = std::max(1u, n);
+               v_align += 'c';
+               niceInsert(MathAtom(new MathArrayInset(m, n, v_align[0], h_align)));
+               return;
+       }
+
+       if (s == "\\over" || s == "\\choose" || s == "\\atop") {
+               MathArray ar = array();
+               MathAtom t = createMathInset(s.substr(1));
+               t->asNestInset()->cell(0).swap(array());
+               pos() = 0;
+               niceInsert(t);
+               popRight();
+               left();
+               return;
+       }
+
+       niceInsert(createMathInset(s.substr(1)));
 }
 
 
-MathParInset * MathedCursor::getCurrentPar() const
+void MathCursor::interpret(char c)
 {
-       return cursor->getPar();
+       //lyxerr << "interpret 2: '" << c << "'\n";
+
+       if (inMacroMode()) {
+               string name = macroName();
+
+               if (name == "\\" && c == '#') {
+                       insert(c, LM_TC_TEX);
+                       return;
+               }
+
+               if (name == "\\" && c == '\\') {
+                       backspace();
+                       interpret("\\backslash");
+                       return;
+               }
+
+               if (name == "\\#" && '1' <= c && c <= '9') {
+                       insert(c, LM_TC_TEX);
+                       macroModeClose();
+                       return;
+               }
+
+               if (isalpha(c)) {
+                       insert(c, LM_TC_TEX);
+                       return;
+               }
+
+               if (name == "\\") {
+                       insert(c, LM_TC_TEX);
+                       macroModeClose();
+                       return;
+               }
+
+               macroModeClose();
+               return;
+       }
+
+       // no macro mode
+       if (c == '^' || c == '_') {
+               const bool up = (c == '^');
+               selCut();
+               if (hasPrevAtom() && prevAtom()->asScriptInset()) {
+                       prevAtom()->asScriptInset()->ensure(up);
+                       pushRight(prevAtom());
+                       pos() = size();
+               } else if (hasNextAtom() && nextAtom()->asScriptInset()) {
+                       nextAtom()->asScriptInset()->ensure(up);
+                       pushLeft(nextAtom());
+                       pos() = 0;
+               } else {
+                       plainInsert(MathAtom(new MathScriptInset(up)));
+                       pushRight(prevAtom());
+               }
+               idx() = up;
+               selPaste();
+               return;
+       }
+
+       if (selection_)
+               selDel();
+
+       if (lastcode_ == LM_TC_TEXTRM) {
+               insert(c, LM_TC_TEXTRM);
+               return;
+       }
+
+       if (c == ' ') {
+               if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
+                       prevAtom()->asSpaceInset()->incSpace();
+                       return;
+               }
+
+               if (mathcursor->popRight())
+                       return;
+
+#warning look here
+                       // this would not work if the inset is in an table!
+                       //bv->text->cursorRight(bv, true);
+                       //result = FINISHED;
+               return;
+       }
+
+       if (strchr("{}", c)) {
+               insert(c, LM_TC_TEX);
+               return;
+       }
+
+       if (strchr("#$%", c)) {
+               insert(MathAtom(new MathSpecialCharInset(c)));  
+               lastcode_ = LM_TC_VAR;
+               return;
+       }
+
+       if (isalpha(c) && (lastcode_ == LM_TC_GREEK || lastcode_ == LM_TC_GREEK1)) {
+               static char const greekl[][26] =
+                       {"alpha", "beta", "chi", "delta", "epsilon", "phi",
+                        "gamma", "eta", "iota", "epsilon", "kappa", "lambda", "mu",
+                        "nu", "omikron", "pi", "vartheta", "rho", "sigma",
+                        "tau", "upsilon", "theta", "omega", "xi", "varphi", "zeta"};
+               static char const greeku[][26] =
+                       {"Alpha", "Beta", "chi", "Delta", "varepsilon", "Phi",
+                        "Gamma", "Eta", "Iota", "Epsilon", "Kappa", "Lambda", "Mu",
+                        "Nu", "Omikron", "Pi", "vartheta", "varrho", "Sigma", "varsigma",
+                        "Upsilon", "Theta", "Omega", "Xi", "Varphi", "Zeta"};
+       
+               latexkeys const * l = 0;        
+               if ('a' <= c && c <= 'z')
+                       l = in_word_set(greekl[c - 'a']);
+               if ('A' <= c && c <= 'Z')
+                       l = in_word_set(greeku[c - 'A']);
+       
+               if (l)
+                       insert(createMathInset(l));
+               else
+                       insert(c, LM_TC_VAR);
+
+#warning greek insert problem? look here!
+               if (lastcode_ == LM_TC_GREEK1)
+                       lastcode_ = LM_TC_VAR;
+               return; 
+       }
+
+       if (c == '\\') {
+               insert(c, LM_TC_TEX);
+               //bv->owner()->message(_("TeX mode"));
+               return; 
+       }
+
+       // no special circumstances, so insert the character without any fuss
+       insert(c, LM_TC_MIN);
 }
 
 
-string const & MathedCursor::getLabel() const
+
+////////////////////////////////////////////////////////////////////////
+
+
+bool operator==(MathCursorPos const & ti, MathCursorPos const & it)
 {
-       return cursor->getLabel();
+       return ti.par_ == it.par_ && ti.idx_ == it.idx_ && ti.pos_ == it.pos_;
 }
 
 
-bool MathedCursor::IsEnd() const
+bool operator<(MathCursorPos const & ti, MathCursorPos const & it)
 {
-       return !cursor->OK();
+       if (ti.par_ != it.par_) {
+               lyxerr << "can't compare cursor and anchor in different insets\n";
+               return true;
+       }
+       if (ti.idx_ != it.idx_)
+               return ti.idx_ < it.idx_;
+       return ti.pos_ < it.pos_;
 }
 
 
-bool MathedCursor::InMacroMode()
+MathArray & MathCursorPos::cell(MathCursor::idx_type idx) const
 {
-       return macro_mode;
+       return (*par_)->cell(idx);
 }
 
 
-bool MathedCursor::Selection()
+MathArray & MathCursorPos::cell() const
 {
-       return selection;
+       return (*par_)->cell(idx_);
 }
 
 
-void MathedCursor::clearLastCode()
+MathXArray & MathCursorPos::xcell(MathCursor::idx_type idx) const
 {
-       lastcode = LM_TC_MIN;
+       return (*par_)->xcell(idx);
 }
 
 
-void MathedCursor::setLastCode(MathedTextCodes t)
+MathXArray & MathCursorPos::xcell() const
 {
-       lastcode = t;
+       return (*par_)->xcell(idx_);
 }
 
 
-MathedTextCodes MathedCursor::getLastCode() const
+MathCursorPos MathCursor::normalAnchor() const
 {
-       return lastcode;
+       // use Anchor on the same level as Cursor
+       MathCursorPos normal = Anchor_[Cursor_.size() - 1];
+       if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
+               // anchor is behind cursor -> move anchor behind the inset
+               ++normal.pos_;
+       }
+       return normal;
 }
+
+