]> git.lyx.org Git - lyx.git/blobdiff - src/mathed/InsetMathGrid.cpp
Check path of Qt tools if qtchooser is detected
[lyx.git] / src / mathed / InsetMathGrid.cpp
index 4360eb61fb7d3c1e347677f0e198c90e7720666e..f2d88a2bdfc21fde7de083f496eb47d71aeed90b 100644 (file)
@@ -3,7 +3,7 @@
  * This file is part of LyX, the document processor.
  * Licence details can be found in the file COPYING.
  *
- * \author André Pönitz
+ * \author André Pönitz
  *
  * Full author contact details are available in file CREDITS.
  */
 
 #include "InsetMathGrid.h"
 
+#include "InsetMathUnknown.h"
 #include "MathData.h"
 #include "MathParser.h"
 #include "MathStream.h"
 #include "MetricsInfo.h"
 
+#include "Buffer.h"
+#include "BufferParams.h"
 #include "BufferView.h"
-#include "CutAndPaste.h"
-#include "FuncStatus.h"
 #include "Cursor.h"
+#include "CutAndPaste.h"
 #include "FuncRequest.h"
+#include "FuncStatus.h"
+#include "TexRow.h"
 
 #include "frontends/Clipboard.h"
 #include "frontends/Painter.h"
@@ -31,8 +35,7 @@
 #include "support/docstream.h"
 #include "support/gettext.h"
 #include "support/lstrings.h"
-
-#include "support/assert.h"
+#include "support/lassert.h"
 
 #include <sstream>
 
@@ -40,6 +43,7 @@ using namespace std;
 using namespace lyx::support;
 
 
+
 namespace lyx {
 
 static docstring verboseHLine(int n)
@@ -61,12 +65,23 @@ static int extractInt(istream & is)
 }
 
 
+static void resetGrid(InsetMathGrid & grid)
+{
+       while (grid.ncols() > 1)
+               grid.delCol(grid.ncols() - 1);
+       while (grid.nrows() > 1)
+               grid.delRow(grid.nrows() - 1);
+       grid.cell(0).erase(0, grid.cell(0).size());
+       grid.setDefaults();
+}
+
+
 
 //////////////////////////////////////////////////////////////
 
 
 InsetMathGrid::CellInfo::CellInfo()
-       : dummy_(false)
+       : multi_(CELL_NORMAL), glue_(0), begin_(0), end_(0)
 {}
 
 
@@ -75,14 +90,15 @@ InsetMathGrid::CellInfo::CellInfo()
 
 
 InsetMathGrid::RowInfo::RowInfo()
-       : lines_(0), skip_(0), allow_newpage_(true)
+       : descent_(0), ascent_(0), offset_(0), lines_(0), skip_(0),
+         allow_newpage_(true)
 {}
 
 
 
-int InsetMathGrid::RowInfo::skipPixels() const
+int InsetMathGrid::RowInfo::skipPixels(MetricsInfo const & mi) const
 {
-       return crskip_.inBP();
+       return crskip_.inPixels(mi.base);
 }
 
 
@@ -91,15 +107,15 @@ int InsetMathGrid::RowInfo::skipPixels() const
 
 
 InsetMathGrid::ColInfo::ColInfo()
-       : align_('c'), lines_(0)
+       : align_('c'), width_(0), offset_(0), lines_(0), skip_(0)
 {}
 
 
 //////////////////////////////////////////////////////////////
 
 
-InsetMathGrid::InsetMathGrid()
-       : InsetMathNest(1),
+InsetMathGrid::InsetMathGrid(Buffer * buf)
+       : InsetMathNest(buf, 1),
          rowinfo_(1 + 1),
                colinfo_(1 + 1),
                cellinfo_(1),
@@ -109,8 +125,8 @@ InsetMathGrid::InsetMathGrid()
 }
 
 
-InsetMathGrid::InsetMathGrid(col_type m, row_type n)
-       : InsetMathNest(m * n),
+InsetMathGrid::InsetMathGrid(Buffer * buf, col_type m, row_type n)
+       : InsetMathNest(buf, m * n),
          rowinfo_(n + 1),
                colinfo_(m + 1),
                cellinfo_(m * n),
@@ -120,8 +136,9 @@ InsetMathGrid::InsetMathGrid(col_type m, row_type n)
 }
 
 
-InsetMathGrid::InsetMathGrid(col_type m, row_type n, char v, docstring const & h)
-       : InsetMathNest(m * n),
+InsetMathGrid::InsetMathGrid(Buffer * buf, col_type m, row_type n, char v,
+       docstring const & h)
+       : InsetMathNest(buf, m * n),
          rowinfo_(n + 1),
          colinfo_(m + 1),
                cellinfo_(m * n),
@@ -156,6 +173,24 @@ void InsetMathGrid::setDefaults()
                colinfo_[col].skip_  = defaultColSpace(col);
                colinfo_[col].special_.clear();
        }
+       for (idx_type idx = 0; idx < nargs(); ++idx)
+               cellinfo_[idx].multi_ = CELL_NORMAL;
+}
+
+
+bool InsetMathGrid::interpretString(Cursor & cur, docstring const & str)
+{
+       if (str == "\\hline") {
+               FuncRequest fr = FuncRequest(LFUN_TABULAR_FEATURE, "add-hline-above");
+               FuncStatus status;
+               if (getStatus(cur, fr, status)) {
+                       if (status.enabled()) {
+                               rowinfo_[cur.row()].lines_++;
+                               return true;
+                       }
+               }
+       }
+       return InsetMathNest::interpretString(cur, str);
 }
 
 
@@ -326,6 +361,23 @@ InsetMathGrid::row_type InsetMathGrid::row(idx_type idx) const
 }
 
 
+InsetMathGrid::col_type InsetMathGrid::ncellcols(idx_type idx) const
+{
+       col_type cols = 1;
+       if (cellinfo_[idx].multi_ == CELL_NORMAL)
+               return cols;
+       // If the cell at idx is already CELL_PART_OF_MULTICOLUMN we return
+       // the number of remaining columns, not the ones of the complete
+       // multicolumn cell. This makes it possible to always go to the next
+       // cell with idx + ncellcols(idx) - 1.
+       row_type const r = row(idx);
+       while (idx+cols < nargs() && row(idx+cols) == r &&
+              cellinfo_[idx+cols].multi_ == CELL_PART_OF_MULTICOLUMN)
+               cols++;
+       return cols;
+}
+
+
 void InsetMathGrid::vcrskip(Length const & crskip, row_type row)
 {
        rowinfo_[row].crskip_ = crskip;
@@ -341,7 +393,12 @@ Length InsetMathGrid::vcrskip(row_type row) const
 void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
 {
        // let the cells adjust themselves
-       InsetMathNest::metrics(mi);
+       for (idx_type i = 0; i < nargs(); ++i) {
+               if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
+                       Dimension dimc;
+                       cell(i).metrics(mi, dimc);
+               }
+       }
 
        BufferView & bv = *mi.base.bv;
 
@@ -350,9 +407,12 @@ void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
                int asc  = 0;
                int desc = 0;
                for (col_type col = 0; col < ncols(); ++col) {
-                       Dimension const & dimc = cell(index(row, col)).dimension(bv);
-                       asc  = max(asc,  dimc.asc);
-                       desc = max(desc, dimc.des);
+                       idx_type const i = index(row, col);
+                       if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
+                               Dimension const & dimc = cell(i).dimension(bv);
+                               asc  = max(asc,  dimc.asc);
+                               desc = max(desc, dimc.des);
+                       }
                }
                rowinfo_[row].ascent_  = asc;
                rowinfo_[row].descent_ = desc;
@@ -364,10 +424,10 @@ void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
        // compute vertical offsets
        rowinfo_[0].offset_ = 0;
        for (row_type row = 1; row <= nrows(); ++row) {
-               rowinfo_[row].offset_  =
-                       rowinfo_[row - 1].offset_  +
+               rowinfo_[row].offset_ =
+                       rowinfo_[row - 1].offset_ +
                        rowinfo_[row - 1].descent_ +
-                       rowinfo_[row - 1].skipPixels() +
+                       rowinfo_[row - 1].skipPixels(mi) +
                        rowsep() +
                        rowinfo_[row].lines_ * hlinesep() +
                        rowinfo_[row].ascent_;
@@ -389,11 +449,33 @@ void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
                rowinfo_[row].offset_ -= h;
 
 
+       // multicolumn cell widths, as a map from first column to width in a
+       // vector of last columns.
+       // This is only used if the grid has more than one row, since for
+       // one-row grids multicolumn cells do not need special handling
+       vector<map<col_type, int> > mcolwidths(ncols());
+
        // compute absolute sizes of horizontal structure
        for (col_type col = 0; col < ncols(); ++col) {
                int wid = 0;
-               for (row_type row = 0; row < nrows(); ++row)
-                       wid = max(wid, cell(index(row, col)).dimension(bv).wid);
+               for (row_type row = 0; row < nrows(); ++row) {
+                       idx_type const i = index(row, col);
+                       if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
+                               int const w = cell(i).dimension(bv).wid;
+                               col_type const cols = ncellcols(i);
+                               if (cols > 1 && nrows() > 1) {
+                                       col_type last = col+cols-1;
+                                       LASSERT(last < ncols(), last = ncols()-1);
+                                       map<col_type, int>::iterator it =
+                                               mcolwidths[last].find(col);
+                                       if (it == mcolwidths[last].end())
+                                               mcolwidths[last][col] = w;
+                                       else
+                                               it->second = max(it->second, w);
+                               } else
+                                       wid = max(wid, w);
+                       }
+               }
                colinfo_[col].width_ = wid;
        }
        colinfo_[ncols()].width_  = 0;
@@ -404,26 +486,55 @@ void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
                colinfo_[col].offset_ =
                        colinfo_[col - 1].offset_ +
                        colinfo_[col - 1].width_ +
-                       colinfo_[col - 1].skip_ +
+                       displayColSpace(col - 1) +
                        colsep() +
                        colinfo_[col].lines_ * vlinesep();
        }
 
+       // increase column widths for multicolumn cells if needed
+       // FIXME: multicolumn lines are not yet considered
+       for (col_type last = 0; last < ncols(); ++last) {
+               map<col_type, int> const & widths = mcolwidths[last];
+               // We increase the width of the last column of the multicol
+               // cell (some sort of left alignment). Since we iterate through
+               // the last and the first columns from left to right, we ensure
+               // that increased widths of previous columns are correctly
+               // taken into account for later columns, thus preventing
+               // unneeded width increasing.
+               for (map<col_type, int>::const_iterator it = widths.begin();
+                    it != widths.end(); ++it) {
+                       int const wid = it->second;
+                       col_type const first = it->first;
+                       int const nextoffset =
+                               colinfo_[first].offset_ +
+                               wid +
+                               displayColSpace(last) +
+                               colsep() +
+                               colinfo_[last+1].lines_ * vlinesep();
+                       int const dx = nextoffset - colinfo_[last+1].offset_;
+                       if (dx > 0) {
+                               colinfo_[last].width_ += dx;
+                               for (col_type col = last + 1; col <= ncols(); ++col)
+                                       colinfo_[col].offset_ += dx;
+                       }
+               }
+       }
+
 
-       dim.wid   =   colinfo_[ncols() - 1].offset_
-                      + colinfo_[ncols() - 1].width_
-                + vlinesep() * colinfo_[ncols()].lines_
-                      + border();
+       dim.wid = colinfo_[ncols() - 1].offset_
+               + colinfo_[ncols() - 1].width_
+               + vlinesep() * colinfo_[ncols()].lines_
+               + border();
 
-       dim.asc  = - rowinfo_[0].offset_
-                      + rowinfo_[0].ascent_
-                + hlinesep() * rowinfo_[0].lines_
-                      + border();
+       dim.asc = - rowinfo_[0].offset_
+               + rowinfo_[0].ascent_
+               + hlinesep() * rowinfo_[0].lines_
+               + border();
 
-       dim.des =   rowinfo_[nrows() - 1].offset_
-                      + rowinfo_[nrows() - 1].descent_
-                + hlinesep() * rowinfo_[nrows()].lines_
-                      + border();
+       dim.des = rowinfo_[nrows() - 1].offset_
+               + rowinfo_[nrows() - 1].descent_
+               + hlinesep() * rowinfo_[nrows()].lines_
+               + border();
 
 
 /*
@@ -477,7 +588,7 @@ void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
        }
 */
        metricsMarkers2(dim);
-       // Cache the inset dimension. 
+       // Cache the inset dimension.
        setDimCache(mi, dim);
 }
 
@@ -494,11 +605,47 @@ void InsetMathGrid::drawWithMargin(PainterInfo & pi, int x, int y,
        Dimension const dim = dimension(*pi.base.bv);
        BufferView const & bv = *pi.base.bv;
 
-       for (idx_type idx = 0; idx < nargs(); ++idx)
-               cell(idx).draw(pi, x + lmargin + cellXOffset(bv, idx),
-                       y + cellYOffset(idx));
+       for (idx_type idx = 0; idx < nargs(); ++idx) {
+               if (cellinfo_[idx].multi_ != CELL_PART_OF_MULTICOLUMN) {
+                       cell(idx).draw(pi,
+                               x + lmargin + cellXOffset(bv, idx),
+                               y + cellYOffset(idx));
+
+                       // draw inner lines cell by cell because of possible multicolumns
+                       // FIXME: multicolumn lines are not yet considered
+                       row_type const r = row(idx);
+                       col_type const c = col(idx);
+                       if (r > 0 && r < nrows()) {
+                               for (unsigned int i = 0; i < rowinfo_[r].lines_; ++i) {
+                                       int yy = y + rowinfo_[r].offset_
+                                               - rowinfo_[r].ascent_
+                                               - i * hlinesep()
+                                               - hlinesep()/2 - rowsep()/2;
+                                       pi.pain.line(
+                                               x + lmargin + colinfo_[c].offset_,
+                                               yy,
+                                               x + lmargin + colinfo_[c+1].offset_,
+                                               yy, Color_foreground);
+                               }
+                       }
+                       if (c > 0 && c < ncols()) {
+                               for (unsigned int i = 0; i < colinfo_[c].lines_; ++i) {
+                                       int xx = x + lmargin
+                                               + colinfo_[c].offset_
+                                               - i * vlinesep()
+                                               - vlinesep()/2 - colsep()/2;
+                                       pi.pain.line(xx,
+                                               rowinfo_[r].offset_ - rowinfo_[r].ascent_,
+                                               xx,
+                                               rowinfo_[r].offset_ + rowinfo_[r].descent_,
+                                               Color_foreground);
+                               }
+                       }
+               }
+       }
 
-       for (row_type row = 0; row <= nrows(); ++row)
+       // draw outer lines in one go
+       for (row_type row = 0; row <= nrows(); row += nrows())
                for (unsigned int i = 0; i < rowinfo_[row].lines_; ++i) {
                        int yy = y + rowinfo_[row].offset_ - rowinfo_[row].ascent_
                                - i * hlinesep() - hlinesep()/2 - rowsep()/2;
@@ -507,7 +654,7 @@ void InsetMathGrid::drawWithMargin(PainterInfo & pi, int x, int y,
                                     Color_foreground);
                }
 
-       for (col_type col = 0; col <= ncols(); ++col)
+       for (col_type col = 0; col <= ncols(); col += ncols())
                for (unsigned int i = 0; i < colinfo_[col].lines_; ++i) {
                        int xx = x + lmargin + colinfo_[col].offset_
                                - i * vlinesep() - vlinesep()/2 - colsep()/2;
@@ -522,20 +669,23 @@ void InsetMathGrid::drawWithMargin(PainterInfo & pi, int x, int y,
 void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
 {
        // let the cells adjust themselves
-       //InsetMathNest::metrics(mi);
        for (idx_type i = 0; i < nargs(); ++i)
-               cell(i).metricsT(mi, dim);
+               if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN)
+                       cell(i).metricsT(mi, dim);
 
        // compute absolute sizes of vertical structure
        for (row_type row = 0; row < nrows(); ++row) {
                int asc  = 0;
                int desc = 0;
                for (col_type col = 0; col < ncols(); ++col) {
-                       //MathData const & c = cell(index(row, col));
-                       // FIXME: BROKEN!
-                       Dimension dimc;
-                       asc  = max(asc,  dimc.ascent());
-                       desc = max(desc, dimc.descent());
+                       idx_type const i = index(row, col);
+                       if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
+                               //MathData const & c = cell(i);
+                               // FIXME: BROKEN!
+                               Dimension dimc;
+                               asc  = max(asc,  dimc.ascent());
+                               desc = max(desc, dimc.descent());
+                       }
                }
                rowinfo_[row].ascent_  = asc;
                rowinfo_[row].descent_ = desc;
@@ -550,7 +700,7 @@ void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
                rowinfo_[row].offset_  =
                        rowinfo_[row - 1].offset_  +
                        rowinfo_[row - 1].descent_ +
-                       //rowinfo_[row - 1].skipPixels() +
+                       //rowinfo_[row - 1].skipPixels(mi) +
                        1 + //rowsep() +
                        //rowinfo_[row].lines_ * hlinesep() +
                        rowinfo_[row].ascent_;
@@ -577,7 +727,9 @@ void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
                int wid = 0;
                for (row_type row = 0; row < nrows(); ++row) {
                        // FIXME: BROKEN!
-                       //wid = max(wid, cell(index(row, col)).width());
+                       //idx_type const i = index(row, col);
+                       //if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN)
+                       //      wid = max(wid, cell(i).width());
                }
                colinfo_[col].width_ = wid;
        }
@@ -589,7 +741,7 @@ void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
                colinfo_[col].offset_ =
                        colinfo_[col - 1].offset_ +
                        colinfo_[col - 1].width_ +
-                       colinfo_[col - 1].skip_ +
+                       displayColSpace(col - 1) +
                        1 ; //colsep() +
                        //colinfo_[col].lines_ * vlinesep();
        }
@@ -615,11 +767,22 @@ void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
 void InsetMathGrid::drawT(TextPainter & /*pain*/, int /*x*/, int /*y*/) const
 {
 //     for (idx_type idx = 0; idx < nargs(); ++idx)
-//             cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
+//             if (cellinfo_[idx].multi_ != CELL_PART_OF_MULTICOLUMN)
+//                     cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
 }
 
 
-docstring InsetMathGrid::eolString(row_type row, bool emptyline, bool fragile) const
+void InsetMathGrid::updateBuffer(ParIterator const & it, UpdateType utype)
+{
+       // pass down
+       for (idx_type idx = 0; idx < nargs(); ++idx)
+               if (cellinfo_[idx].multi_ != CELL_PART_OF_MULTICOLUMN)
+                       cell(idx).updateBuffer(it, utype);
+}
+
+
+docstring InsetMathGrid::eolString(row_type row, bool fragile,
+               bool /*latex*/, bool last_eoln) const
 {
        docstring eol;
 
@@ -631,13 +794,13 @@ docstring InsetMathGrid::eolString(row_type row, bool emptyline, bool fragile) c
        // make sure an upcoming '[' does not break anything
        if (row + 1 < nrows()) {
                MathData const & c = cell(index(row + 1, 0));
-               if (c.size() && c.front()->getChar() == '[')
+               if (!c.empty() && c.front()->getChar() == '[')
                        //eol += "[0pt]";
                        eol += "{}";
        }
 
        // only add \\ if necessary
-       if (eol.empty() && row + 1 == nrows() && (nrows() == 1 || !emptyline))
+       if (eol.empty() && row + 1 == nrows() && (nrows() == 1 || !last_eoln))
                return docstring();
 
        return (fragile ? "\\protect\\\\" : "\\\\") + eol;
@@ -662,17 +825,6 @@ void InsetMathGrid::addRow(row_type row)
 }
 
 
-void InsetMathGrid::appendRow()
-{
-       rowinfo_.push_back(RowInfo());
-       //cells_.insert(cells_.end(), ncols(), MathData());
-       for (col_type col = 0; col < ncols(); ++col) {
-               cells_.push_back(cells_type::value_type());
-               cellinfo_.push_back(CellInfo());
-       }
-}
-
-
 void InsetMathGrid::delRow(row_type row)
 {
        if (nrows() == 1)
@@ -752,7 +904,7 @@ void InsetMathGrid::delCol(col_type col)
 
 void InsetMathGrid::copyCol(col_type col)
 {
-       addCol(col);
+       addCol(col+1);
        for (row_type row = 0; row < nrows(); ++row)
                cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
 }
@@ -771,14 +923,16 @@ void InsetMathGrid::swapCol(col_type col)
 
 int InsetMathGrid::cellXOffset(BufferView const & bv, idx_type idx) const
 {
+       if (cellinfo_[idx].multi_ == CELL_PART_OF_MULTICOLUMN)
+               return 0;
        col_type c = col(idx);
        int x = colinfo_[c].offset_;
-       char align = colinfo_[c].align_;
+       char align = displayColAlign(idx);
        Dimension const & celldim = cell(idx).dimension(bv);
        if (align == 'r' || align == 'R')
-               x += colinfo_[c].width_ - celldim.wid;
+               x += cellWidth(idx) - celldim.wid;
        if (align == 'c' || align == 'C')
-               x += (colinfo_[c].width_ - celldim.wid) / 2;
+               x += (cellWidth(idx) - celldim.wid) / 2;
        return x;
 }
 
@@ -789,6 +943,27 @@ int InsetMathGrid::cellYOffset(idx_type idx) const
 }
 
 
+int InsetMathGrid::cellWidth(idx_type idx) const
+{
+       switch (cellinfo_[idx].multi_) {
+       case CELL_NORMAL:
+               return colinfo_[col(idx)].width_;
+       case CELL_BEGIN_OF_MULTICOLUMN: {
+               col_type c1 = col(idx);
+               col_type c2 = c1 + ncellcols(idx);
+               return colinfo_[c2].offset_
+                       - colinfo_[c1].offset_
+                       - displayColSpace(c2)
+                       - colsep()
+                       - colinfo_[c2].lines_ * vlinesep();
+       }
+       case CELL_PART_OF_MULTICOLUMN:
+               return 0;
+       }
+       return 0;
+}
+
+
 bool InsetMathGrid::idxUpDown(Cursor & cur, bool up) const
 {
        if (up) {
@@ -800,6 +975,11 @@ bool InsetMathGrid::idxUpDown(Cursor & cur, bool up) const
                        return false;
                cur.idx() += ncols();
        }
+       // If we are in a multicolumn cell, move to the "real" cell
+       while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
+               LASSERT(cur.idx() > 0, return false);
+               --cur.idx();
+       }
        cur.pos() = cur.cell().x2pos(&cur.bv(), cur.x_target() - cur.cell().xo(cur.bv()));
        return true;
 }
@@ -811,6 +991,11 @@ bool InsetMathGrid::idxBackward(Cursor & cur) const
        if (cur.col() == 0)
                return false;
        --cur.idx();
+       // If we are in a multicolumn cell, move to the "real" cell
+       while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
+               LASSERT(cur.idx() > 0, return false);
+               --cur.idx();
+       }
        cur.pos() = cur.lastpos();
        return true;
 }
@@ -822,6 +1007,13 @@ bool InsetMathGrid::idxForward(Cursor & cur) const
        if (cur.col() + 1 == ncols())
                return false;
        ++cur.idx();
+       // If we are in a multicolumn cell, move to the next cell
+       while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
+               // leave matrix if at the back edge
+               if (cur.col() + 1 == ncols())
+                       return false;
+               ++cur.idx();
+       }
        cur.pos() = 0;
        return true;
 }
@@ -839,6 +1031,11 @@ bool InsetMathGrid::idxFirst(Cursor & cur) const
                default:
                        cur.idx() = ((nrows() - 1) / 2) * ncols();
        }
+       // If we are in a multicolumn cell, move to the "real" cell
+       while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
+               LASSERT(cur.idx() > 0, return false);
+               --cur.idx();
+       }
        cur.pos() = 0;
        return true;
 }
@@ -856,6 +1053,11 @@ bool InsetMathGrid::idxLast(Cursor & cur) const
                default:
                        cur.idx() = ((nrows() - 1) / 2 + 1) * ncols() - 1;
        }
+       // If we are in a multicolumn cell, move to the "real" cell
+       while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
+               LASSERT(cur.idx() > 0, return false);
+               --cur.idx();
+       }
        cur.pos() = cur.lastpos();
        return true;
 }
@@ -873,7 +1075,7 @@ bool InsetMathGrid::idxDelete(idx_type & idx)
 
        // try to delete entire sequence of ncols() empty cells if possible
        for (idx_type i = idx; i < idx + ncols(); ++i)
-               if (cell(i).size())
+               if (!cell(i).empty())
                        return false;
 
        // move cells if necessary
@@ -906,9 +1108,15 @@ void InsetMathGrid::idxGlue(idx_type idx)
                        delRow(row(idx) + 1);
                }
        } else {
-               cell(idx).append(cell(idx + 1));
+               idx_type idx_next = idx + 1;
+               while (idx_next < nargs() &&
+                      cellinfo_[idx_next].multi_ == CELL_PART_OF_MULTICOLUMN)
+                       ++idx_next;
+               if (idx_next < nargs())
+                       cell(idx).append(cell(idx_next));
+               col_type oldcol = c + 1;
                for (col_type cc = c + 2; cc < ncols(); ++cc)
-                       cell(idx - c + cc - 1) = cell(idx - c + cc);
+                       cell(idx - oldcol + cc) = cell(idx - oldcol + 1 + cc);
                cell(idx - c + ncols() - 1).clear();
        }
 }
@@ -938,14 +1146,26 @@ bool InsetMathGrid::idxBetween(idx_type idx, idx_type from, idx_type to) const
 }
 
 
-
 void InsetMathGrid::normalize(NormalStream & os) const
 {
        os << "[grid ";
        for (row_type row = 0; row < nrows(); ++row) {
                os << "[row ";
-               for (col_type col = 0; col < ncols(); ++col)
-                       os << "[cell " << cell(index(row, col)) << ']';
+               for (col_type col = 0; col < ncols(); ++col) {
+                       idx_type const i = index(row, col);
+                       switch (cellinfo_[i].multi_) {
+                       case CELL_NORMAL:
+                               os << "[cell " << cell(i) << ']';
+                               break;
+                       case CELL_BEGIN_OF_MULTICOLUMN:
+                               os << "[cell colspan="
+                                  << static_cast<int>(ncellcols(i)) << ' '
+                                  << cell(i) << ']';
+                               break;
+                       case CELL_PART_OF_MULTICOLUMN:
+                               break;
+                       }
+               }
                os << ']';
        }
        os << ']';
@@ -954,39 +1174,135 @@ void InsetMathGrid::normalize(NormalStream & os) const
 
 void InsetMathGrid::mathmlize(MathStream & os) const
 {
-       os << MTag("mtable");
+       bool const havetable = nrows() > 1 || ncols() > 1;
+       if (havetable)
+               os << MTag("mtable");
+       char const * const celltag = havetable ? "mtd" : "mrow";
        for (row_type row = 0; row < nrows(); ++row) {
-               os << MTag("mtr");
-               for (col_type col = 0; col < ncols(); ++col)
-                       os << cell(index(row, col));
-               os << ETag("mtr");
+               if (havetable)
+                       os << MTag("mtr");
+               for (col_type col = 0; col < ncols(); ++col) {
+                       idx_type const i = index(row, col);
+                       if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
+                               col_type const cellcols = ncellcols(i);
+                               ostringstream attr;
+                               if (havetable && cellcols > 1)
+                                       attr << "colspan='" << cellcols << '\'';
+                               os << MTag(celltag, attr.str());
+                               os << cell(index(row, col));
+                               os << ETag(celltag);
+                       }
+               }
+               if (havetable)
+                       os << ETag("mtr");
+       }
+       if (havetable)
+               os << ETag("mtable");
+}
+
+
+// FIXME XHTML
+// We need to do something about alignment here.
+void InsetMathGrid::htmlize(HtmlStream & os, string attrib) const
+{
+       bool const havetable = nrows() > 1 || ncols() > 1;
+       if (!havetable) {
+               os << cell(index(0, 0));
+               return;
+       }
+       os << MTag("table", attrib);
+       for (row_type row = 0; row < nrows(); ++row) {
+               os << MTag("tr");
+               for (col_type col = 0; col < ncols(); ++col) {
+                       idx_type const i = index(row, col);
+                       if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
+                               col_type const cellcols = ncellcols(i);
+                               ostringstream attr;
+                               if (cellcols > 1)
+                                       attr << "colspan='" << cellcols << '\'';
+                               os << MTag("td", attr.str());
+                               os << cell(index(row, col));
+                               os << ETag("td");
+                       }
+               }
+               os << ETag("tr");
        }
-       os << ETag("mtable");
+       os << ETag("table");
+}
+
+
+void InsetMathGrid::htmlize(HtmlStream & os) const
+{
+       htmlize(os, "class='mathtable'");
 }
 
 
 void InsetMathGrid::write(WriteStream & os) const
 {
+       write(os, 0, 0, nrows(), ncols());
+}
+
+void InsetMathGrid::write(WriteStream & os,
+                         row_type beg_row, col_type beg_col,
+                         row_type end_row, col_type end_col) const
+{
+       MathEnsurer ensurer(os, false);
        docstring eol;
-       for (row_type row = 0; row < nrows(); ++row) {
+       for (row_type row = beg_row; row < end_row; ++row) {
                os << verboseHLine(rowinfo_[row].lines_);
-               // don't write & and empty cells at end of line
+               // don't write & and empty cells at end of line,
+               // unless there are vertical lines
                col_type lastcol = 0;
                bool emptyline = true;
-               for (col_type col = 0; col < ncols(); ++col)
-                       if (!cell(index(row, col)).empty()) {
+               bool last_eoln = true;
+               for (col_type col = beg_col; col < end_col; ++col) {
+                       idx_type const idx = index(row, col);
+                       bool const empty_cell = cell(idx).empty();
+                       if (!empty_cell || cellinfo_[idx].multi_ != CELL_NORMAL)
+                               last_eoln = false;
+                       if (!empty_cell || cellinfo_[idx].multi_ != CELL_NORMAL ||
+                           colinfo_[col + 1].lines_) {
                                lastcol = col + 1;
                                emptyline = false;
                        }
-               for (col_type col = 0; col < lastcol; ++col)
-                       os << cell(index(row, col)) << eocString(col, lastcol);
-               eol = eolString(row, emptyline, os.fragile());
+               }
+               for (col_type col = beg_col; col < end_col;) {
+                       int nccols = 1;
+                       idx_type const idx = index(row, col);
+                       RowEntry entry = TexRow::mathEntry(id(),idx);
+                       os.texrow().start(entry);
+                       if (col >= lastcol) {
+                               ++col;
+                               continue;
+                       }
+                       Changer dummy = os.changeRowEntry(entry);
+                       if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN) {
+                               size_t s = col + 1;
+                               while (s < ncols() &&
+                                      cellinfo_[index(row, s)].multi_ == CELL_PART_OF_MULTICOLUMN)
+                                       s++;
+                               nccols = s - col;
+                               os << "\\multicolumn{" << nccols
+                                  << "}{" << cellinfo_[idx].align_
+                                  << "}{";
+                       }
+                       os << cell(idx);
+                       if (os.pendingBrace())
+                               ModeSpecifier specifier(os, TEXT_MODE);
+                       if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN)
+                               os << '}';
+                       os << eocString(col + nccols - 1, lastcol);
+                       col += nccols;
+               }
+               eol = eolString(row, os.fragile(), os.latex(), last_eoln);
                os << eol;
                // append newline only if line wasn't completely empty
-               // and this was not the last line in the grid
-               if (!emptyline && row + 1 < nrows())
+               // and the formula is not written on a single line
+               bool const empty = emptyline && eol.empty();
+               if (!empty && nrows() > 1)
                        os << "\n";
        }
+       // @TODO use end_row instead of nrows() ?
        docstring const s = verboseHLine(rowinfo_[nrows()].lines_);
        if (!s.empty()) {
                if (eol.empty()) {
@@ -1037,23 +1353,46 @@ void InsetMathGrid::splitCell(Cursor & cur)
        ar.erase(0, cur.pos());
        cur.cell().erase(cur.pos(), cur.lastpos());
        ++cur.idx();
+       while (cur.idx() << nargs() &&
+              cellinfo_[cur.idx()].multi_ == CELL_BEGIN_OF_MULTICOLUMN)
+               ++cur.idx();
        cur.pos() = 0;
        cur.cell().insert(0, ar);
 }
 
 
+char InsetMathGrid::displayColAlign(idx_type idx) const
+{
+       if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN) {
+               // align_ may also contain lines like "||r|", so this is
+               // not complete, but we catch at least the simple cases.
+               if (cellinfo_[idx].align_ == "c")
+                       return 'c';
+               if (cellinfo_[idx].align_ == "l")
+                       return 'l';
+               if (cellinfo_[idx].align_ == "r")
+                       return 'r';
+       }
+       return colinfo_[col(idx)].align_;
+}
+
+
+int InsetMathGrid::displayColSpace(col_type col) const
+{
+       return colinfo_[col].skip_;
+}
+
 void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
 {
        //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
-       switch (cmd.action) {
+
+       Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
+
+       FuncCode const act = cmd.action();
+       switch (act) {
 
        // insert file functions
-       case LFUN_LINE_DELETE:
-               // FIXME: We use recordUndoInset when a change reflects more
-               // than one cell, because recordUndo does not work for
-               // multiple cells. Unfortunately this puts the cursor in front
-               // of the inset after undo. This is (especilally for large
-               // grids) annoying.
+       case LFUN_LINE_DELETE_FORWARD:
                cur.recordUndoInset();
                //autocorrect_ = false;
                //macroModeClose();
@@ -1076,7 +1415,7 @@ void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
 
        case LFUN_CELL_BACKWARD:
                // See below.
-               cur.selection() = false;
+               cur.selection(false);
                if (!idxPrev(cur)) {
                        cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
                        cur.undispatched();
@@ -1086,7 +1425,7 @@ void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
        case LFUN_CELL_FORWARD:
                // Can't handle selection by additional 'shift' as this is
                // hard bound to LFUN_CELL_BACKWARD
-               cur.selection() = false;
+               cur.selection(false);
                if (!idxNext(cur)) {
                        cmd = FuncRequest(LFUN_FINISHED_FORWARD);
                        cur.undispatched();
@@ -1104,11 +1443,12 @@ void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
 
                // split cell
                splitCell(cur);
-               swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
+               if (ncols() > 1)
+                       swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
                if (cur.idx() > 0)
                        --cur.idx();
                cur.pos() = cur.lastpos();
-
+               cur.forceBufferUpdate();
                //mathcursor->normalize();
                //cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
                break;
@@ -1208,7 +1548,7 @@ void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
                        docstring & special = colinfo_[cur.col()].special_;
                        if (!special.empty()) {
                                docstring::size_type i = special.rfind('|');
-                               LASSERT(i != docstring::npos, /**/);
+                               LASSERT(i != docstring::npos, break);
                                special.erase(i, 1);
                        }
                }
@@ -1217,7 +1557,7 @@ void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
                        docstring & special = colinfo_[cur.col()+1].special_;
                        if (!special.empty()) {
                                docstring::size_type i = special.find('|');
-                               LASSERT(i != docstring::npos, /**/);
+                               LASSERT(i != docstring::npos, break);
                                special.erase(i, 1);
                        }
                }
@@ -1226,31 +1566,54 @@ void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
                        break;
                }
                // perhaps this should be FINISHED_BACKWARD -- just for clarity?
-               lyxerr << "returning FINISHED_LEFT" << endl;
+               //lyxerr << "returning FINISHED_LEFT" << endl;
                break;
        }
 
+       case LFUN_CLIPBOARD_PASTE:
+               parseflg |= Parse::VERBATIM;
+               // fall through
        case LFUN_PASTE: {
+               if (cur.currentMode() <= TEXT_MODE)
+                       parseflg |= Parse::TEXTMODE;
                cur.message(_("Paste"));
                cap::replaceSelection(cur);
                docstring topaste;
                if (cmd.argument().empty() && !theClipboard().isInternal())
-                       topaste = theClipboard().getAsText();
+                       topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
                else {
                        idocstringstream is(cmd.argument());
                        int n = 0;
                        is >> n;
-                       topaste = cap::selection(n);
+                       topaste = cap::selection(n, buffer().params().documentClassPtr());
                }
-               InsetMathGrid grid(1, 1);
+               InsetMathGrid grid(buffer_, 1, 1);
                if (!topaste.empty())
-                       mathed_parse_normal(grid, topaste);
+                       if ((topaste.size() == 1 && isAscii(topaste))
+                           || !mathed_parse_normal(grid, topaste, parseflg)) {
+                               resetGrid(grid);
+                               mathed_parse_normal(grid, topaste, parseflg | Parse::VERBATIM);
+                       }
 
+               bool hline_enabled = false;
+               FuncRequest fr = FuncRequest(LFUN_TABULAR_FEATURE, "add-hline-above");
+               FuncStatus status;
+               if (getStatus(cur, fr, status))
+                       hline_enabled = status.enabled();
                if (grid.nargs() == 1) {
                        // single cell/part of cell
-                       cur.recordUndo();
+                       cur.recordUndoInset();
                        cur.cell().insert(cur.pos(), grid.cell(0));
                        cur.pos() += grid.cell(0).size();
+                       if (hline_enabled)
+                               rowinfo_[cur.row()].lines_ += grid.rowinfo_[0].lines_;
+                       else {
+                               for (unsigned int l = 0; l < grid.rowinfo_[0].lines_; ++l) {
+                                        cur.cell().insert(0,
+                                               MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
+                                        cur.pos()++;
+                               }
+                       }
                } else {
                        // multiple cells
                        cur.recordUndoInset();
@@ -1263,6 +1626,15 @@ void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
                                        idx_type i = index(r + cur.row(), c + col(cur.idx()));
                                        cell(i).insert(0, grid.cell(grid.index(r, c)));
                                }
+                               if (hline_enabled)
+                                       rowinfo_[r].lines_ += grid.rowinfo_[r].lines_;
+                               else {
+                                       for (unsigned int l = 0; l < grid.rowinfo_[r].lines_; ++l) {
+                                               idx_type i = index(r + cur.row(), 0);
+                                               cell(i).insert(0,
+                                                       MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
+                                       }
+                               }
                                // append the left over horizontal cells to the last column
                                idx_type i = index(r + cur.row(), ncols() - 1);
                                for (InsetMath::col_type c = numcols; c < grid.ncols(); ++c)
@@ -1270,24 +1642,38 @@ void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
                        }
                        // append the left over vertical cells to the last _cell_
                        idx_type i = nargs() - 1;
-                       for (row_type r = numrows; r < grid.nrows(); ++r)
+                       for (row_type r = numrows; r < grid.nrows(); ++r) {
                                for (col_type c = 0; c < grid.ncols(); ++c)
                                        cell(i).append(grid.cell(grid.index(r, c)));
+                               if (hline_enabled)
+                                       rowinfo_[r].lines_ += grid.rowinfo_[r].lines_;
+                               else {
+                                       for (unsigned int l = 0; l < grid.rowinfo_[r].lines_; ++l) {
+                                               cell(i).insert(0,
+                                                       MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
+                                       }
+                               }
+                       }
                }
                cur.clearSelection(); // bug 393
+               // FIXME audit setBuffer calls
+               cur.inset().setBuffer(*buffer_);
+               cur.forceBufferUpdate();
                cur.finishUndo();
                break;
        }
 
-       case LFUN_LINE_BEGIN_SELECT:
        case LFUN_LINE_BEGIN:
-       case LFUN_WORD_BACKWARD_SELECT:
        case LFUN_WORD_BACKWARD:
-       case LFUN_WORD_LEFT_SELECT:
        case LFUN_WORD_LEFT:
-               cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
-                               cmd.action == LFUN_WORD_LEFT_SELECT ||
-                               cmd.action == LFUN_LINE_BEGIN_SELECT);
+               cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
+               // fall through
+       case LFUN_LINE_BEGIN_SELECT:
+       case LFUN_WORD_BACKWARD_SELECT:
+       case LFUN_WORD_LEFT_SELECT:
+               cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
+                               act == LFUN_WORD_LEFT_SELECT ||
+                               act == LFUN_LINE_BEGIN_SELECT);
                cur.macroModeClose();
                if (cur.pos() != 0) {
                        cur.pos() = 0;
@@ -1303,15 +1689,17 @@ void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
                }
                break;
 
-       case LFUN_WORD_FORWARD_SELECT:
        case LFUN_WORD_FORWARD:
-       case LFUN_WORD_RIGHT_SELECT:
        case LFUN_WORD_RIGHT:
-       case LFUN_LINE_END_SELECT:
        case LFUN_LINE_END:
-               cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
-                               cmd.action == LFUN_WORD_RIGHT_SELECT ||
-                               cmd.action == LFUN_LINE_END_SELECT);
+               cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
+               // fall through
+       case LFUN_WORD_FORWARD_SELECT:
+       case LFUN_WORD_RIGHT_SELECT:
+       case LFUN_LINE_END_SELECT:
+               cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
+                               act == LFUN_WORD_RIGHT_SELECT ||
+                               act == LFUN_LINE_END_SELECT);
                cur.macroModeClose();
                cur.clearTargetX();
                if (cur.pos() != cur.lastpos()) {
@@ -1337,17 +1725,24 @@ void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
 bool InsetMathGrid::getStatus(Cursor & cur, FuncRequest const & cmd,
                FuncStatus & status) const
 {
-       switch (cmd.action) {
+       switch (cmd.action()) {
        case LFUN_TABULAR_FEATURE: {
-               string const s = to_utf8(cmd.argument());
+               string s = cmd.getArg(0);
+               if (&cur.inset() != this) {
+                       // Table actions requires that the cursor is _inside_ the
+                       // table.
+                       status.setEnabled(false);
+                       status.message(from_utf8(N_("Cursor not in table")));
+                       return true;
+               }
                if (nrows() <= 1 && (s == "delete-row" || s == "swap-row")) {
-                       status.enabled(false);
+                       status.setEnabled(false);
                        status.message(from_utf8(N_("Only one row")));
                        return true;
                }
                if (ncols() <= 1 &&
                    (s == "delete-column" || s == "swap-column")) {
-                       status.enabled(false);
+                       status.setEnabled(false);
                        status.message(from_utf8(N_("Only one column")));
                        return true;
                }
@@ -1355,7 +1750,7 @@ bool InsetMathGrid::getStatus(Cursor & cur, FuncRequest const & cmd,
                     s == "delete-hline-above") ||
                    (rowinfo_[cur.row() + 1].lines_ == 0 &&
                     s == "delete-hline-below")) {
-                       status.enabled(false);
+                       status.setEnabled(false);
                        status.message(from_utf8(N_("No hline to delete")));
                        return true;
                }
@@ -1364,37 +1759,40 @@ bool InsetMathGrid::getStatus(Cursor & cur, FuncRequest const & cmd,
                     s == "delete-vline-left") ||
                    (colinfo_[cur.col() + 1].lines_ == 0 &&
                     s == "delete-vline-right")) {
-                       status.enabled(false);
+                       status.setEnabled(false);
                        status.message(from_utf8(N_("No vline to delete")));
                        return true;
                }
                if (s == "valign-top" || s == "valign-middle" ||
                    s == "valign-bottom" || s == "align-left" ||
-                   s == "align-right" || s == "align-center" ||
-                   s == "append-row" || s == "delete-row" ||
+                   s == "align-right" || s == "align-center") {
+                       status.setEnabled(true);
+                       char const ha = horizontalAlignment(cur.col());
+                       char const va = verticalAlignment();
+                       status.setOnOff((s == "align-left" && ha == 'l')
+                                       || (s == "align-right"   && ha == 'r')
+                                       || (s == "align-center"  && ha == 'c')
+                                       || (s == "valign-top"    && va == 't')
+                                       || (s == "valign-bottom" && va == 'b')
+                                       || (s == "valign-middle" && va == 'c'));
+                       return true;
+               }
+               if (s == "append-row" || s == "delete-row" ||
                    s == "copy-row" || s == "swap-row" ||
                    s == "add-hline-above" || s == "add-hline-below" ||
                    s == "delete-hline-above" || s == "delete-hline-below" ||
                    s == "append-column" || s == "delete-column" ||
                    s == "copy-column" || s == "swap-column" ||
                    s == "add-vline-left" || s == "add-vline-right" ||
-                   s == "delete-vline-left" || s == "delete-vline-right")
-                       status.enabled(true);
-               else {
-                       status.enabled(false);
+                   s == "delete-vline-left" || s == "delete-vline-right") {
+                       status.setEnabled(true);
+               else {
+                       status.setEnabled(false);
                        status.message(bformat(
-                               from_utf8(N_("Unknown tabular feature '%1$s'")), lyx::from_ascii(s)));
+                           from_utf8(N_("Unknown tabular feature '%1$s'")),
+                           from_utf8(s)));
                }
 
-               char const ha = horizontalAlignment(cur.col());
-               char const va = verticalAlignment();
-               status.setOnOff((s == "align-left" && ha == 'l')
-                          || (s == "align-right"   && ha == 'r')
-                          || (s == "align-center"  && ha == 'c')
-                          || (s == "valign-top"    && va == 't')
-                          || (s == "valign-bottom" && va == 'b')
-                          || (s == "valign-middle" && va == 'm'));
-
 #if 0
                // FIXME: What did this code do?
                // Please check whether it is still needed!
@@ -1412,23 +1810,89 @@ bool InsetMathGrid::getStatus(Cursor & cur, FuncRequest const & cmd,
                        break;
                }
                status.setOnOff(cmd.argument()[0] == v_align_);
-               status.enabled(true);
+               status.setEnabled(true);
 #endif
                return true;
        }
 
        case LFUN_CELL_SPLIT:
-               status.enabled(true);
+               status.setEnabled(cur.idx() != cur.lastidx());
                return true;
 
        case LFUN_CELL_BACKWARD:
        case LFUN_CELL_FORWARD:
-               status.enabled(true);
+               status.setEnabled(true);
                return true;
 
        default:
-               return InsetMathNest::getStatus(cur, cmd, status);
+               break;
+       }
+       return InsetMathNest::getStatus(cur, cmd, status);
+}
+
+
+// static
+char InsetMathGrid::colAlign(HullType type, col_type col)
+{
+       switch (type) {
+       case hullEqnArray:
+               return "rcl"[col % 3];
+
+       case hullMultline:
+       case hullGather:
+               return 'c';
+
+       case hullAlign:
+       case hullAlignAt:
+       case hullXAlignAt:
+       case hullXXAlignAt:
+       case hullFlAlign:
+               return "rl"[col & 1];
+
+       case hullUnknown:
+       case hullNone:
+       case hullSimple:
+       case hullEquation:
+       case hullRegexp:
+               return 'c';
+       }
+       // avoid warning
+       return 'c';
+}
+
+
+//static
+int InsetMathGrid::colSpace(HullType type, col_type col)
+{
+       int alignInterSpace = 0;
+       switch (type) {
+       case hullUnknown:
+       case hullNone:
+       case hullSimple:
+       case hullEquation:
+       case hullMultline:
+       case hullGather:
+       case hullRegexp:
+               return 0;
+
+       case hullEqnArray:
+               return 5;
+
+       case hullAlign:
+               alignInterSpace = 20;
+               break;
+       case hullAlignAt:
+               alignInterSpace = 0;
+               break;
+       case hullXAlignAt:
+               alignInterSpace = 40;
+               break;
+       case hullXXAlignAt:
+       case hullFlAlign:
+               alignInterSpace = 60;
+               break;
        }
+       return (col % 2) ? alignInterSpace : 0;
 }