]> git.lyx.org Git - lyx.git/blobdiff - src/insets/InsetTabular.cpp
InsetTabular.cpp: output the caption for docbook
[lyx.git] / src / insets / InsetTabular.cpp
index 49b048ae0fb96deb882dca0fd11e63fea89167e7..daf4a3634b73d9777087592c3becf31e2fc77eb2 100644 (file)
@@ -3,14 +3,14 @@
  * This file is part of LyX, the document processor.
  * Licence details can be found in the file COPYING.
  *
- * \author Lars Gullik Bjønnes
+ * \author Lars Gullik Bjønnes
  * \author Matthias Ettrich
- * \author José Matos
+ * \author José Matos
  * \author Jean-Marc Lasgouttes
  * \author Angus Leeming
  * \author John Levon
- * \author André Pönitz
- * \author Jürgen Vigna
+ * \author André Pönitz
+ * \author Jürgen Vigna
  *
  * Full author contact details are available in file CREDITS.
  */
@@ -55,6 +55,7 @@
 #include "support/docstream.h"
 #include "support/FileName.h"
 #include "support/gettext.h"
+#include "support/lassert.h"
 #include "support/lstrings.h"
 
 #include <boost/scoped_ptr.hpp>
@@ -150,6 +151,7 @@ TabularFeature tabularFeature[] =
        { Tabular::SET_LTLASTFOOT, "set-ltlastfoot" },
        { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot" },
        { Tabular::SET_LTNEWPAGE, "set-ltnewpage" },
+       { Tabular::TOGGLE_LTCAPTION, "toggle-ltcaption" },
        { Tabular::SET_SPECIAL_COLUMN, "set-special-column" },
        { Tabular::SET_SPECIAL_MULTI, "set-special-multi" },
        { Tabular::SET_BOOKTABS, "set-booktabs" },
@@ -158,6 +160,9 @@ TabularFeature tabularFeature[] =
        { Tabular::SET_BOTTOM_SPACE, "set-bottom-space" },
        { Tabular::SET_INTERLINE_SPACE, "set-interline-space" },
        { Tabular::SET_BORDER_LINES, "set-border-lines" },
+       { Tabular::TABULAR_VALIGN_TOP, "tabular-valign-top"},
+       { Tabular::TABULAR_VALIGN_MIDDLE, "tabular-valign-middle"},
+       { Tabular::TABULAR_VALIGN_BOTTOM, "tabular-valign-bottom"},
        { Tabular::LAST_ACTION, "" }
 };
 
@@ -470,7 +475,7 @@ string const featureAsString(Tabular::Feature feature)
 /////////////////////////////////////////////////////////////////////
 
 
-Tabular::CellData::CellData(Buffer const & buf, Tabular const & table)
+Tabular::CellData::CellData(Buffer & buf)
        : cellno(0),
          width(0),
          multicolumn(Tabular::CELL_NORMAL),
@@ -482,10 +487,10 @@ Tabular::CellData::CellData(Buffer const & buf, Tabular const & table)
          right_line(false),
          usebox(BOX_NONE),
          rotate(false),
-         inset(new InsetTableCell(buf, this, &table))
+         inset(new InsetTableCell(buf))
 {
        inset->setBuffer(const_cast<Buffer &>(buf));
-       inset->paragraphs().back().setLayout(buf.params().documentClass().emptyLayout());
+       inset->paragraphs().back().setLayout(buf.params().documentClass().plainLayout());
 }
 
 
@@ -505,17 +510,14 @@ Tabular::CellData::CellData(CellData const & cs)
          p_width(cs.p_width),
          inset(dynamic_cast<InsetTableCell *>(cs.inset->clone()))
 {
-       inset->setCellData(this);
 }
 
-
 Tabular::CellData & Tabular::CellData::operator=(CellData cs)
 {
        swap(cs);
        return *this;
 }
 
-
 void Tabular::CellData::swap(CellData & rhs)
 {
        std::swap(cellno, rhs.cellno);
@@ -545,7 +547,8 @@ Tabular::RowData::RowData()
          endfirsthead(false),
          endfoot(false),
          endlastfoot(false),
-         newpage(false)
+         newpage(false),
+         caption(false)
 {}
 
 
@@ -564,40 +567,50 @@ Tabular::ltType::ltType()
 {}
 
 
-Tabular::Tabular()
+Tabular::Tabular(Buffer & buffer, row_type rows_arg, col_type columns_arg)
 {
-       // unusable now!
+       init(buffer, rows_arg, columns_arg);
 }
 
 
-Tabular::Tabular(Buffer const & buffer, row_type rows_arg, col_type columns_arg)
+void Tabular::setBuffer(Buffer & buffer)
 {
-       init(buffer, rows_arg, columns_arg);
+       buffer_ = &buffer;
+       size_t row_count = row_info.size();
+       size_t column_count = column_info.size();
+       // set silly default lines
+       for (row_type i = 0; i < row_count; ++i)
+               for (col_type j = 0; j < column_count; ++j)
+                       cell_info[i][j].inset->setBuffer(*buffer_);
 }
 
 
 // activates all lines and sets all widths to 0
-void Tabular::init(Buffer const & buf, row_type rows_arg,
+void Tabular::init(Buffer & buf, row_type rows_arg,
                      col_type columns_arg)
 {
        buffer_ = &buf;
        row_info = row_vector(rows_arg);
        column_info = column_vector(columns_arg);
-       cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf, *this)));
+       cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf)));
        row_info.reserve(10);
        column_info.reserve(10);
        cell_info.reserve(100);
        updateIndexes();
        is_long_tabular = false;
+       tabular_valignment = LYX_VALIGN_MIDDLE;
        rotate = false;
        use_booktabs = false;
+       size_t row_count = row_info.size();
+       size_t column_count = column_info.size();
        // set silly default lines
-       for (row_type i = 0; i < rowCount(); ++i)
-               for (col_type j = 0; j < columnCount(); ++j) {
+       for (row_type i = 0; i < row_count; ++i)
+               for (col_type j = 0; j < column_count; ++j) {
+                       cell_info[i][j].inset->setBuffer(*buffer_);
                        cell_info[i][j].top_line = true;
                        cell_info[i][j].left_line = true;
-                       cell_info[i][j].bottom_line = i == 0 || i == rowCount() - 1;
-                       cell_info[i][j].right_line = j == columnCount() - 1;
+                       cell_info[i][j].bottom_line = i == 0 || i == row_count - 1;
+                       cell_info[i][j].right_line = j == column_count - 1;
                }
 }
 
@@ -612,14 +625,14 @@ void Tabular::appendRow(idx_type const cell)
        // now set the values of the row before
        row_info[row] = row_info[row + 1];
 
-       row_type const nrows = rowCount();
-       col_type const ncols = columnCount();
+       row_type const nrows = row_info.size();
+       col_type const ncols = column_info.size();
 
        cell_vvector old(nrows - 1);
        for (row_type i = 0; i < nrows - 1; ++i)
                swap(cell_info[i], old[i]);
 
-       cell_info = cell_vvector(nrows, cell_vector(ncols, CellData(buffer(), *this)));
+       cell_info = cell_vvector(nrows, cell_vector(ncols, CellData(buffer())));
 
        for (row_type i = 0; i <= row; ++i)
                swap(cell_info[i], old[i]);
@@ -631,14 +644,13 @@ void Tabular::appendRow(idx_type const cell)
                // inherit line settings
                idx_type const i = cellIndex(row + 1, c);
                idx_type const j = cellIndex(row, c);
-               setLeftLine(i, isPartOfMultiColumn(row, c) ? false : leftLine(j));
-               if (cell_info[row][c].multicolumn == CELL_NORMAL || c == ncols - 1
-                       || (c + 1 < ncols 
-                       && cell_info[row][c].multicolumn != CELL_NORMAL
-                       && cell_info[row][c + 1].multicolumn == CELL_NORMAL))
-                       setRightLine(i, rightLine(j));
-               else
-                       setRightLine(i, false);
+               setLeftLine(i, leftLine(j));
+               setRightLine(i, rightLine(j));
+               setTopLine(i, topLine(j));
+               if (topLine(j) && bottomLine(j)) {
+                       setBottomLine(i, true);
+                       setBottomLine(j, false);
+               }
                // mark track changes
                if (bp.trackChanges)
                        cellInfo(i).inset->setChange(Change(Change::INSERTED));
@@ -649,7 +661,7 @@ void Tabular::appendRow(idx_type const cell)
 void Tabular::deleteRow(row_type const row)
 {
        // Not allowed to delete last row
-       if (rowCount() == 1)
+       if (row_info.size() == 1)
                return;
 
        row_info.erase(row_info.begin() + row);
@@ -664,7 +676,7 @@ void Tabular::copyRow(row_type const row)
        cell_info.insert(cell_info.begin() + row, cell_info[row]);
 
        if (buffer().params().trackChanges)
-               for (col_type j = 0; j < columnCount(); ++j)
+               for (col_type j = 0; j < column_info.size(); ++j)
                        cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
 
        updateIndexes();
@@ -673,31 +685,37 @@ void Tabular::copyRow(row_type const row)
 
 void Tabular::appendColumn(idx_type const cell)
 {
-       col_type const column = cellColumn(cell);
-       column_vector::iterator cit = column_info.begin() + column + 1;
+       col_type const c = cellColumn(cell);
+       column_vector::iterator cit = column_info.begin() + c + 1;
        column_info.insert(cit, ColumnData());
-       row_type const nrows = rowCount();
-       col_type const ncols = columnCount();
+       row_type const nrows = row_info.size();
        // set the column values of the column before
-       column_info[column + 1] = column_info[column];
+       column_info[c + 1] = column_info[c];
 
        for (row_type r = 0; r < nrows; ++r) {
-               cell_info[r].insert(cell_info[r].begin() + column + 1, 
-                       CellData(buffer(), *this));
-               col_type c = column + 2;
-               while (c < ncols 
-                       && cell_info[r][c].multicolumn == CELL_PART_OF_MULTICOLUMN) {
-                       cell_info[r][c].multicolumn = CELL_NORMAL;
-                       ++c;
-               }
+               cell_info[r].insert(cell_info[r].begin() + c + 1, 
+                       CellData(buffer()));
+#if 0
+// FIXME: This code does not work. It deletes the cell's content and
+// it triggers an assertion if the cursor is at pos > 0.
+               if (cell_info[r][c].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
+                       cell_info[r][c + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
+               else
+                       cell_info[r][c + 1].multicolumn = cell_info[r][c].multicolumn;
+#endif
        }
        updateIndexes();
        for (row_type r = 0; r < nrows; ++r) {
                // inherit line settings
-               idx_type const i = cellIndex(r, column + 1);
-               idx_type const j = cellIndex(r, column);
+               idx_type const i = cellIndex(r, c + 1);
+               idx_type const j = cellIndex(r, c);
                setBottomLine(i, bottomLine(j));
                setTopLine(i, topLine(j));
+               setLeftLine(i, leftLine(j));
+               if (rightLine(j) && rightLine(j)) {
+                       setRightLine(i, true);
+                       setRightLine(j, false);
+               }
                //
                cellInfo(i).inset->clear();
                if (buffer().params().trackChanges)
@@ -709,19 +727,20 @@ void Tabular::appendColumn(idx_type const cell)
 void Tabular::deleteColumn(col_type const column)
 {
        // Not allowed to delete last column
-       if (columnCount() == 1)
+       if (column_info.size() == 1)
                return;
 
-       column_info.erase(column_info.begin() + column);
-       for (row_type i = 0; i < rowCount(); ++i) {
+       size_t const row_count = row_info.size();
+       for (row_type i = 0; i < row_count; ++i) {
                // Care about multicolumn cells
-               if (column + 1 < columnCount() &&
+               if (column + 1 < column_info.size() &&
                    cell_info[i][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
                    cell_info[i][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
                        cell_info[i][column + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
                }
                cell_info[i].erase(cell_info[i].begin() + column);
        }
+       column_info.erase(column_info.begin() + column);
        updateIndexes();
 }
 
@@ -731,11 +750,12 @@ void Tabular::copyColumn(col_type const column)
        BufferParams const & bp = buffer().params();
        column_info.insert(column_info.begin() + column, column_info[column]);
 
-       for (row_type i = 0; i < rowCount(); ++i)
+       size_t row_count = row_info.size();
+       for (row_type i = 0; i < row_count; ++i)
                cell_info[i].insert(cell_info[i].begin() + column, cell_info[i][column]);
 
        if (bp.trackChanges)
-               for (row_type i = 0; i < rowCount(); ++i)
+               for (row_type i = 0; i < row_count; ++i)
                        cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
        updateIndexes();
 }
@@ -743,8 +763,8 @@ void Tabular::copyColumn(col_type const column)
 
 void Tabular::updateIndexes()
 {
-       col_type ncols = columnCount();
-       row_type nrows = rowCount();
+       col_type ncols = column_info.size();
+       row_type nrows = row_info.size();
        numberofcells = 0;
        for (row_type row = 0; row < nrows; ++row)
                for (col_type column = 0; column < ncols; ++column) {
@@ -762,22 +782,18 @@ void Tabular::updateIndexes()
                                continue;
                        rowofcell[i] = row;
                        columnofcell[i] = column;
+                       setFixedWidth(row, column);
+                       updateContentAlignment(row, column);
                        ++i;
                }
 }
 
 
-Tabular::idx_type Tabular::cellCount() const
-{
-       return numberofcells;
-}
-
-
 Tabular::idx_type Tabular::numberOfCellsInRow(idx_type const cell) const
 {
        row_type const row = cellRow(cell);
        idx_type result = 0;
-       for (col_type i = 0; i < columnCount(); ++i)
+       for (col_type i = 0; i < column_info.size(); ++i)
                if (cell_info[row][i].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
                        ++result;
        return result;
@@ -818,7 +834,7 @@ bool Tabular::topAlreadyDrawn(idx_type cell) const
        if (row == 0)
                return false;
        idx_type i = cellIndex(row - 1, cellColumn(cell));
-       return !rowBottomLine(row - 1) && bottomLine(i);
+       return !rowTopLine(row) && bottomLine(i);
 }
 
 
@@ -834,13 +850,13 @@ bool Tabular::leftAlreadyDrawn(idx_type cell) const
 
 bool Tabular::isLastRow(idx_type cell) const
 {
-       return cellRow(cell) == rowCount() - 1;
+       return cellRow(cell) == row_info.size() - 1;
 }
 
 
 int Tabular::getAdditionalHeight(row_type row) const
 {
-       if (!row || row >= rowCount())
+       if (!row || row >= row_info.size())
                return 0;
 
        int const interline_space = row_info[row - 1].interline_space_default ?
@@ -856,7 +872,7 @@ int Tabular::getAdditionalWidth(idx_type cell) const
 {
        col_type const nextcol = cellColumn(cell) + columnSpan(cell);
        if (rightLine(cell) 
-               && nextcol < columnCount() && leftLine(cellIndex(cellRow(cell), nextcol)))
+               && nextcol < column_info.size() && leftLine(cellIndex(cellRow(cell), nextcol)))
                return WIDTH_OF_LINE;
        return 0;
 }
@@ -875,8 +891,8 @@ int Tabular::columnWidth(idx_type cell) const
 
 bool Tabular::updateColumnWidths()
 {
-       col_type const ncols = columnCount();
-       row_type const nrows = rowCount();
+       col_type const ncols = column_info.size();
+       row_type const nrows = row_info.size();
        bool update = false;
        // for each col get max of single col cells
        for(col_type c = 0; c < ncols; ++c) {
@@ -916,7 +932,7 @@ bool Tabular::updateColumnWidths()
 
 int Tabular::width() const
 {
-       col_type const ncols = columnCount();
+       col_type const ncols = column_info.size();
        int width = 0;
        for (col_type i = 0; i < ncols; ++i)
                width += column_info[i].width;
@@ -938,6 +954,7 @@ void Tabular::setAlignment(idx_type cell, LyXAlignment align,
                column_info[cellColumn(cell)].alignment = align;
        if (!onlycolumn)
                cellInfo(cell).alignment = align;
+       cellInset(cell).get()->setContentAlignment(align);
 }
 
 
@@ -961,6 +978,7 @@ namespace {
 void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
 {
        inset->setAutoBreakRows(fixedWidth);
+       inset->toggleFixedWidth(fixedWidth);
        if (fixedWidth)
                return;
 
@@ -973,7 +991,7 @@ void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
        cur.push(*inset);
        // undo information has already been recorded
        inset->getText(0)->setLayout(cur.bv().buffer(), 0, cur.lastpit() + 1,
-                       bp.documentClass().emptyLayoutName());
+                       bp.documentClass().plainLayoutName());
        cur.pop();
 }
 
@@ -986,7 +1004,7 @@ void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
        col_type const j = cellColumn(cell);
 
        column_info[j].p_width = width;
-       for (row_type i = 0; i < rowCount(); ++i) {
+       for (row_type i = 0; i < row_info.size(); ++i) {
                idx_type const cell = cellIndex(i, j);
                // because of multicolumns
                toggleFixedWidth(cur, cellInset(cell).get(),
@@ -1001,6 +1019,23 @@ void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
 }
 
 
+bool Tabular::setFixedWidth(row_type r, col_type c)
+{
+       bool const multicol = cell_info[r][c].multicolumn != CELL_NORMAL;
+       bool const fixed_width = (!column_info[c].p_width.zero() && !multicol)
+             || (multicol && !cell_info[r][c].p_width.zero());
+       cell_info[r][c].inset->toggleFixedWidth(fixed_width);
+       return fixed_width;
+}
+
+
+void Tabular::updateContentAlignment(row_type r, col_type c)
+{
+       cell_info[r][c].inset->setContentAlignment(
+               getAlignment(cellIndex(r, c)));
+}
+
+
 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
                Length const & width)
 {
@@ -1085,27 +1120,45 @@ bool Tabular::rowBottomLine(row_type r) const
 
 bool Tabular::columnLeftLine(col_type c) const
 {
-       bool all_cols_set = true;
-       row_type const nrows = rowCount();
-       for (row_type r = 0; all_cols_set && r < nrows; ++r) {
+       if (use_booktabs)
+               return false;
+
+       int nrows_left = 0;
+       int total = 0;
+       row_type const nrows = row_info.size();
+       for (row_type r = 0; r < nrows; ++r) {
                idx_type i = cellIndex(r, c);
-               if (c == cellColumn(i))
-                       all_cols_set = cellInfo(i).left_line;
+               if (c == cellColumn(i)) {
+                       ++total;
+                       bool right = c > 0 && cellInfo(cellIndex(r, c - 1)).right_line;
+                       if (cellInfo(i).left_line || right)
+                               ++nrows_left;
+               }
        }
-       return all_cols_set;
+       return 2 * nrows_left >= total;
 }
 
 
 bool Tabular::columnRightLine(col_type c) const
 {
-       bool all_cols_set = true;
-       row_type const nrows = rowCount();
-       for (row_type r = 0; all_cols_set && r < nrows; ++r) {
+       if (use_booktabs)
+               return false;
+
+       int nrows_right = 0;
+       int total = 0;
+       row_type const nrows = row_info.size();
+       for (row_type r = 0; r < nrows; ++r) {
                idx_type i = cellIndex(r, c);
-               if (c == cellColumn(i) + columnSpan(i) - 1)
-                       all_cols_set = cellInfo(i).right_line;
+               if (c == cellColumn(i) + columnSpan(i) - 1) {
+                       ++total;
+                       bool left = (c + 1 < column_info.size() 
+                               && cellInfo(cellIndex(r, c + 1)).left_line)
+                               || c + 1 == column_info.size();
+                       if (cellInfo(i).right_line && left)
+                               ++nrows_right;
+               }
        }
-       return all_cols_set;
+       return 2 * nrows_right >= total;
 }
 
 
@@ -1134,28 +1187,6 @@ Length const Tabular::getPWidth(idx_type cell) const
 }
 
 
-Length const Tabular::getColumnPWidth(idx_type cell) const
-{
-       return column_info[cellColumn(cell)].p_width;
-}
-
-
-Length const Tabular::getMColumnPWidth(idx_type cell) const
-{
-       if (isMultiColumn(cell))
-               return cellInfo(cell).p_width;
-       return Length();
-}
-
-
-docstring const Tabular::getAlignSpecial(idx_type cell, int what) const
-{
-       if (what == SET_SPECIAL_MULTI)
-               return cellInfo(cell).align_special;
-       return column_info[cellColumn(cell)].align_special;
-}
-
-
 int Tabular::cellWidth(idx_type cell) const
 {
        return cellInfo(cell).width;
@@ -1193,30 +1224,30 @@ bool Tabular::isFirstCellInRow(idx_type cell) const
 
 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
 {
-       if (row > rowCount() - 1)
-               row = rowCount() - 1;
+       if (row > row_info.size() - 1)
+               row = row_info.size() - 1;
        return cell_info[row][0].cellno;
 }
 
 
 bool Tabular::isLastCellInRow(idx_type cell) const
 {
-       return cellRightColumn(cell) == columnCount() - 1;
+       return cellRightColumn(cell) == column_info.size() - 1;
 }
 
 
 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
 {
-       if (row > rowCount() - 1)
-               row = rowCount() - 1;
-       return cell_info[row][columnCount() - 1].cellno;
+       if (row > row_info.size() - 1)
+               row = row_info.size() - 1;
+       return cell_info[row][column_info.size() - 1].cellno;
 }
 
 
 Tabular::row_type Tabular::cellRow(idx_type cell) const
 {
-       if (cell >= cellCount())
-               return rowCount() - 1;
+       if (cell >= numberofcells)
+               return row_info.size() - 1;
        if (cell == npos)
                return 0;
        return rowofcell[cell];
@@ -1225,10 +1256,10 @@ Tabular::row_type Tabular::cellRow(idx_type cell) const
 
 Tabular::col_type Tabular::cellColumn(idx_type cell) const
 {
-       if (cell >= cellCount())
-               return columnCount() - 1;
+       if (cell >= numberofcells)
+               return column_info.size() - 1;
        if (cell == npos)
-               return 0;
+               return 0;       
        return columnofcell[cell];
 }
 
@@ -1237,7 +1268,7 @@ Tabular::col_type Tabular::cellRightColumn(idx_type cell) const
 {
        row_type const row = cellRow(cell);
        col_type column = cellColumn(cell);
-       while (column < columnCount() - 1 &&
+       while (column < column_info.size() - 1 &&
                   cell_info[row][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN)
                ++column;
        return column;
@@ -1249,14 +1280,15 @@ void Tabular::write(ostream & os) const
        // header line
        os << "<lyxtabular"
           << write_attribute("version", 3)
-          << write_attribute("rows", rowCount())
-          << write_attribute("columns", columnCount())
+          << write_attribute("rows", row_info.size())
+          << write_attribute("columns", column_info.size())
           << ">\n";
        // global longtable options
        os << "<features"
           << write_attribute("rotate", rotate)
           << write_attribute("booktabs", use_booktabs)
           << write_attribute("islongtable", is_long_tabular)
+          << write_attribute("tabularvalignment", tabular_valignment)
           << write_attribute("firstHeadTopDL", endfirsthead.topDL)
           << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
           << write_attribute("firstHeadEmpty", endfirsthead.empty)
@@ -1268,7 +1300,7 @@ void Tabular::write(ostream & os) const
           << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
           << write_attribute("lastFootEmpty", endlastfoot.empty)
           << ">\n";
-       for (col_type j = 0; j < columnCount(); ++j) {
+       for (col_type j = 0; j < column_info.size(); ++j) {
                os << "<column"
                   << write_attribute("alignment", column_info[j].alignment)
                   << write_attribute("valignment", column_info[j].valignment)
@@ -1276,7 +1308,7 @@ void Tabular::write(ostream & os) const
                   << write_attribute("special", column_info[j].align_special)
                   << ">\n";
        }
-       for (row_type i = 0; i < rowCount(); ++i) {
+       for (row_type i = 0; i < row_info.size(); ++i) {
                static const string def("default");
                os << "<row";
                if (row_info[i].top_space_default)
@@ -1296,8 +1328,9 @@ void Tabular::write(ostream & os) const
                   << write_attribute("endfoot", row_info[i].endfoot)
                   << write_attribute("endlastfoot", row_info[i].endlastfoot)
                   << write_attribute("newpage", row_info[i].newpage)
+                  << write_attribute("caption", row_info[i].caption)
                   << ">\n";
-               for (col_type j = 0; j < columnCount(); ++j) {
+               for (col_type j = 0; j < column_info.size(); ++j) {
                        os << "<cell"
                           << write_attribute("multicolumn", cell_info[i][j].multicolumn)
                           << write_attribute("alignment", cell_info[i][j].alignment)
@@ -1329,14 +1362,14 @@ void Tabular::read(Lexer & lex)
 
        l_getline(is, line);
        if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
-               BOOST_ASSERT(false);
+               LASSERT(false, /**/);
                return;
        }
 
        int version;
        if (!getTokenValue(line, "version", version))
                return;
-       BOOST_ASSERT(version >= 2);
+       LASSERT(version >= 2, /**/);
 
        int rows_arg;
        if (!getTokenValue(line, "rows", rows_arg))
@@ -1354,6 +1387,7 @@ void Tabular::read(Lexer & lex)
        getTokenValue(line, "rotate", rotate);
        getTokenValue(line, "booktabs", use_booktabs);
        getTokenValue(line, "islongtable", is_long_tabular);
+       getTokenValue(line, "tabularvalignment", tabular_valignment);
        getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
        getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
        getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
@@ -1365,7 +1399,7 @@ void Tabular::read(Lexer & lex)
        getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
        getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
 
-       for (col_type j = 0; j < columnCount(); ++j) {
+       for (col_type j = 0; j < column_info.size(); ++j) {
                l_getline(is,line);
                if (!prefixIs(line,"<column")) {
                        lyxerr << "Wrong tabular format (expected <column ...> got"
@@ -1378,7 +1412,7 @@ void Tabular::read(Lexer & lex)
                getTokenValue(line, "special", column_info[j].align_special);
        }
 
-       for (row_type i = 0; i < rowCount(); ++i) {
+       for (row_type i = 0; i < row_info.size(); ++i) {
                l_getline(is, line);
                if (!prefixIs(line, "<row")) {
                        lyxerr << "Wrong tabular format (expected <row ...> got"
@@ -1396,7 +1430,8 @@ void Tabular::read(Lexer & lex)
                getTokenValue(line, "endfoot", row_info[i].endfoot);
                getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
                getTokenValue(line, "newpage", row_info[i].newpage);
-               for (col_type j = 0; j < columnCount(); ++j) {
+               getTokenValue(line, "caption", row_info[i].caption);
+               for (col_type j = 0; j < column_info.size(); ++j) {
                        l_getline(is, line);
                        if (!prefixIs(line, "<cell")) {
                                lyxerr << "Wrong tabular format (expected <cell ...> got"
@@ -1413,9 +1448,11 @@ void Tabular::read(Lexer & lex)
                        getTokenValue(line, "rotate", cell_info[i][j].rotate);
                        getTokenValue(line, "usebox", cell_info[i][j].usebox);
                        getTokenValue(line, "width", cell_info[i][j].p_width);
+                       setFixedWidth(i,j);
                        getTokenValue(line, "special", cell_info[i][j].align_special);
                        l_getline(is, line);
                        if (prefixIs(line, "\\begin_inset")) {
+                               cell_info[i][j].inset->setBuffer(*buffer_);
                                cell_info[i][j].inset->read(lex);
                                l_getline(is, line);
                        }
@@ -1477,7 +1514,7 @@ void Tabular::setMultiColumn(idx_type cell, idx_type number)
 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
 {
        row_type const row = cellRow(cell);
-       col_type const ncols = columnCount();
+       col_type const ncols = column_info.size();
        idx_type result = 1;
        col_type column = cellColumn(cell) + 1;
        while (column < ncols && isPartOfMultiColumn(row, column)) {
@@ -1498,7 +1535,7 @@ Tabular::idx_type Tabular::unsetMultiColumn(idx_type cell)
        if (cell_info[row][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN) {
                cell_info[row][column].multicolumn = CELL_NORMAL;
                ++column;
-               while (column < columnCount() &&
+               while (column < column_info.size() &&
                           cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
                {
                        cell_info[row][column].multicolumn = CELL_NORMAL;
@@ -1511,42 +1548,6 @@ Tabular::idx_type Tabular::unsetMultiColumn(idx_type cell)
 }
 
 
-void Tabular::setBookTabs(bool what)
-{
-       use_booktabs = what;
-}
-
-
-bool Tabular::useBookTabs() const
-{
-       return use_booktabs;
-}
-
-
-void Tabular::setLongTabular(bool what)
-{
-       is_long_tabular = what;
-}
-
-
-bool Tabular::isLongTabular() const
-{
-       return is_long_tabular;
-}
-
-
-void Tabular::setRotateTabular(bool flag)
-{
-       rotate = flag;
-}
-
-
-bool Tabular::getRotateTabular() const
-{
-       return rotate;
-}
-
-
 void Tabular::setRotateCell(idx_type cell, bool flag)
 {
        cellInfo(cell).rotate = flag;
@@ -1563,8 +1564,8 @@ bool Tabular::needRotating() const
 {
        if (rotate)
                return true;
-       for (row_type i = 0; i < rowCount(); ++i)
-               for (col_type j = 0; j < columnCount(); ++j)
+       for (row_type i = 0; i < row_info.size(); ++i)
+               for (col_type j = 0; j < column_info.size(); ++j)
                        if (cell_info[i][j].rotate)
                                return true;
        return false;
@@ -1573,7 +1574,7 @@ bool Tabular::needRotating() const
 
 bool Tabular::isLastCell(idx_type cell) const
 {
-       if (cell + 1 < cellCount())
+       if (cell + 1 < numberofcells)
                return false;
        return true;
 }
@@ -1589,7 +1590,7 @@ Tabular::idx_type Tabular::cellAbove(idx_type cell) const
 
 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
 {
-       if (cellRow(cell) + 1 < rowCount())
+       if (cellRow(cell) + 1 < row_info.size())
                return cell_info[cellRow(cell)+1][cellColumn(cell)].cellno;
        return cell;
 }
@@ -1598,8 +1599,8 @@ Tabular::idx_type Tabular::cellBelow(idx_type cell) const
 Tabular::idx_type Tabular::cellIndex(row_type row,
                                               col_type column) const
 {
-       BOOST_ASSERT(column != npos && column < columnCount() &&
-                    row    != npos && row    < rowCount());
+       BOOST_ASSERT(column != npos && column < column_info.size()
+               && row != npos && row < row_info.size());
        return cell_info[row][column].cellno;
 }
 
@@ -1610,10 +1611,12 @@ void Tabular::setUsebox(idx_type cell, BoxType type)
 }
 
 
+// FIXME: Remove this routine because we cannot insert \parboxes when the user
+// adds line breaks, see bug 4886.
 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
 {
-       if (column_info[cellColumn(cell)].p_width.zero() &&
-               !(isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
+       if ((!column_info[cellColumn(cell)].p_width.zero() && !isMultiColumn(cell)) ||
+               (isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
                return BOX_NONE;
        if (cellInfo(cell).usebox > 1)
                return cellInfo(cell).usebox;
@@ -1700,7 +1703,7 @@ bool Tabular::getLTNewPage(row_type row) const
 
 bool Tabular::haveLTHead() const
 {
-       for (row_type i = 0; i < rowCount(); ++i)
+       for (row_type i = 0; i < row_info.size(); ++i)
                if (row_info[i].endhead)
                        return true;
        return false;
@@ -1711,7 +1714,7 @@ bool Tabular::haveLTFirstHead() const
 {
        if (endfirsthead.empty)
                return false;
-       for (row_type i = 0; i < rowCount(); ++i)
+       for (row_type i = 0; i < row_info.size(); ++i)
                if (row_info[i].endfirsthead)
                        return true;
        return false;
@@ -1720,7 +1723,7 @@ bool Tabular::haveLTFirstHead() const
 
 bool Tabular::haveLTFoot() const
 {
-       for (row_type i = 0; i < rowCount(); ++i)
+       for (row_type i = 0; i < row_info.size(); ++i)
                if (row_info[i].endfoot)
                        return true;
        return false;
@@ -1731,18 +1734,56 @@ bool Tabular::haveLTLastFoot() const
 {
        if (endlastfoot.empty)
                return false;
-       for (row_type i = 0; i < rowCount(); ++i)
+       for (row_type i = 0; i < row_info.size(); ++i)
                if (row_info[i].endlastfoot)
                        return true;
        return false;
 }
 
 
+Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
+{
+       idx_type i = getFirstCellInRow(row);
+       if (what) {
+               setMultiColumn(i, numberOfCellsInRow(i));
+               setTopLine(i, false);
+               setBottomLine(i, false);
+               setLeftLine(i, false);
+               setRightLine(i, false);
+               // When a row is set as caption, then also insert a caption. Otherwise
+               // the LaTeX output is broken, when the user don't add a caption.
+               dispatch(FuncRequest(LFUN_CAPTION_INSERT));
+       } else {
+               unsetMultiColumn(i);
+               // FIXME: when unsetting a caption row, also all existing captions
+               // in this row must be dissolved, see (bug 5754)
+               // dispatch(FuncRequest(LFUN_INSET_DISSOLVE, "caption-insert"));
+       }
+       row_info[row].caption = what;
+       return i;
+}
+
+
+bool Tabular::ltCaption(row_type row) const
+{
+       return row_info[row].caption;
+}
+
+
+bool Tabular::haveLTCaption() const
+{
+       for (row_type i = 0; i < row_info.size(); ++i)
+               if (row_info[i].caption)
+                       return true;
+       return false;
+}
+
+
 // end longtable support functions
 
 void Tabular::setRowAscent(row_type row, int height)
 {
-       if (row >= rowCount() || row_info[row].ascent == height)
+       if (row >= row_info.size() || row_info[row].ascent == height)
                return;
        row_info[row].ascent = height;
 }
@@ -1750,7 +1791,7 @@ void Tabular::setRowAscent(row_type row, int height)
 
 void Tabular::setRowDescent(row_type row, int height)
 {
-       if (row >= rowCount() || row_info[row].descent == height)
+       if (row >= row_info.size() || row_info[row].descent == height)
                return;
        row_info[row].descent = height;
 }
@@ -1758,7 +1799,7 @@ void Tabular::setRowDescent(row_type row, int height)
 
 int Tabular::rowAscent(row_type row) const
 {
-       if (row >= rowCount())
+       if (row >= row_info.size())
                return 0;
        return row_info[row].ascent;
 }
@@ -1766,7 +1807,7 @@ int Tabular::rowAscent(row_type row) const
 
 int Tabular::rowDescent(row_type row) const
 {
-       BOOST_ASSERT(row < rowCount());
+       LASSERT(row < row_info.size(), /**/);
        return row_info[row].descent;
 }
 
@@ -1774,7 +1815,7 @@ int Tabular::rowDescent(row_type row) const
 int Tabular::height() const
 {
        int height = 0;
-       for (row_type row = 0; row < rowCount(); ++row)
+       for (row_type row = 0; row < row_info.size(); ++row)
                height += rowAscent(row) + rowDescent(row) +
                        getAdditionalHeight(row);
        return height;
@@ -1783,80 +1824,112 @@ int Tabular::height() const
 
 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
 {
-       BOOST_ASSERT(row < rowCount());
-       BOOST_ASSERT(column < columnCount());
+       LASSERT(row < row_info.size(), /**/);
+       LASSERT(column < column_info.size(), /**/);
        return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
 }
 
 
-int Tabular::TeXTopHLine(odocstream & os, row_type row) const
+int Tabular::TeXTopHLine(odocstream & os, row_type row, string const lang) const
 {
-       // FIXME: assert or return 0 as in TeXBottomHLine()?
-       BOOST_ASSERT(row != npos);
-       BOOST_ASSERT(row < rowCount());
-
-       idx_type const fcell = getFirstCellInRow(row);
-       idx_type const n = numberOfCellsInRow(fcell) + fcell;
-       idx_type tmp = 0;
+       // we only output complete row lines and the 1st row here, the rest
+       // is done in Tabular::TeXBottomHLine(...)
 
-       for (idx_type i = fcell; i < n; ++i) {
-               if (topLine(i))
-                       ++tmp;
+       // get for each column the topline (if any)
+       col_type const ncols = column_info.size();
+       vector<bool> topline;
+       col_type nset = 0;
+       for (col_type c = 0; c < ncols; ++c) {
+               topline.push_back(topLine(cellIndex(row, c)));
+               if (topline[c])
+                       ++nset;
        }
-       if (use_booktabs && row == 0) {
-               if (topLine(fcell))
-                       os << "\\toprule ";
-       } else if (tmp == n - fcell) {
-               os << (use_booktabs ? "\\midrule " : "\\hline ");
-       } else if (tmp) {
-               for (idx_type i = fcell; i < n; ++i) {
-                       if (topLine(i)) {
-                               os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
-                                  << cellColumn(i) + 1
-                                  << '-'
-                                  << cellRightColumn(i) + 1
-                                  << "} ";
+
+       // do nothing if empty first row, or incomplete row line after
+       if ((row == 0 && nset == 0) || (row > 0 && nset != ncols))
+               return 0;
+
+       // only output complete row lines and the 1st row's clines
+       if (nset == ncols) {
+               if (use_booktabs) {
+                       os << (row == 0 ? "\\toprule " : "\\midrule ");
+               } else {
+                       os << "\\hline ";
+               }
+       } else if (row == 0) {
+               for (col_type c = 0; c < ncols; ++c) {
+                       if (topline[c]) {
+                               //babel makes the "-" character an active one, so we have to suppress this here
+                               //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
+                               if (lang == "slovak" || lang == "czech")
+                                       os << (use_booktabs ? "\\expandafter\\cmidrule\\expandafter{\\expandafter" :
+                                                             "\\expandafter\\cline\\expandafter{\\expandafter")
+                                                                                 << c + 1 << "\\string-";
+                               else
+                                       os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 << '-';
+                               // get to last column of line span
+                               while (c < ncols && topline[c])
+                                       ++c;
+                               os << c << "} ";
                        }
                }
-       } else {
-               return 0;
        }
        os << "\n";
        return 1;
 }
 
 
-int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
+int Tabular::TeXBottomHLine(odocstream & os, row_type row, string const lang) const
 {
-       // FIXME: return 0 or assert as in TeXTopHLine()?
-       if (row == npos || row >= rowCount())
-               return 0;
+       // we output bottomlines of row r and the toplines of row r+1
+       // if the latter do not span the whole tabular
 
-       idx_type const fcell = getFirstCellInRow(row);
-       idx_type const n = numberOfCellsInRow(fcell) + fcell;
-       idx_type tmp = 0;
+       // get the bottomlines of row r, and toplines in next row
+       bool lastrow = row == row_info.size() - 1;
+       col_type const ncols = column_info.size();
+       vector<bool> bottomline, topline;
+       bool nextrowset = true;
+       for (col_type c = 0; c < ncols; ++c) {
+               bottomline.push_back(bottomLine(cellIndex(row, c)));
+               topline.push_back(!lastrow && topLine(cellIndex(row + 1, c)));
+               nextrowset &= topline[c];
+       }
 
-       for (idx_type i = fcell; i < n; ++i) {
-               if (bottomLine(i))
-                       ++tmp;
+       // combine this row's bottom lines and next row's toplines if necessary
+       col_type nset = 0;
+       for (col_type c = 0; c < ncols; ++c) {
+               if (!nextrowset)
+                       bottomline[c] = bottomline[c] || topline[c];
+               if (bottomline[c])
+                       ++nset;
        }
-       if (use_booktabs && row == rowCount() - 1) {
-               if (bottomLine(fcell))
-                       os << "\\bottomrule";
-       } else if (tmp == n - fcell) {
-               os << (use_booktabs ? "\\midrule" : "\\hline");
-       } else if (tmp) {
-               for (idx_type i = fcell; i < n; ++i) {
-                       if (bottomLine(i)) {
-                               os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
-                                  << cellColumn(i) + 1
-                                  << '-'
-                                  << cellRightColumn(i) + 1
-                                  << "} ";
+
+       // do nothing if empty, OR incomplete row line with a topline in next row
+       if (nset == 0 || (nextrowset && nset != ncols))
+               return 0;
+
+       if (nset == ncols) {
+               if (use_booktabs)
+                       os << (lastrow ? "\\bottomrule" : "\\midrule");
+               else
+                       os << "\\hline";
+       } else {
+               for (col_type c = 0; c < ncols; ++c) {
+                       if (bottomline[c]) {
+                               //babel makes the "-" character an active one, so we have to suppress this here
+                               //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
+                               if (lang == "slovak" || lang == "czech")
+                                       os << (use_booktabs ? "\\expandafter\\cmidrule\\expandafter{\\expandafter" :
+                                                             "\\expandafter\\cline\\expandafter{\\expandafter")
+                                                                                 << c + 1 << "\\string-";
+                               else
+                                       os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 << '-';
+                               // get to last column of line span
+                               while (c < ncols && bottomline[c])
+                                       ++c;
+                               os << c << "} ";
                        }
                }
-       } else {
-               return 0;
        }
        os << "\n";
        return 1;
@@ -1866,34 +1939,49 @@ int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
 int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol) const
 {
        int ret = 0;
+       row_type const r = cellRow(cell);
+       if (is_long_tabular && row_info[r].caption)
+               return ret;
 
        Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
        LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
        // figure out how to set the lines
        // we always set double lines to the right of the cell
-       row_type const r = cellRow(cell);
        col_type const c = cellColumn(cell);
        col_type const nextcol = c + columnSpan(cell);
-       bool prevcellright = c > 0 && rightLine(cellIndex(r, c - 1));
-       bool forceleft = ismulticol && !prevcellright && leftLine(cell);
-       bool nextcolleft = nextcol < columnCount() && columnLeftLine(nextcol);
-       bool coldouble = columnRightLine(c) && nextcolleft;
-       bool nextcellleft = nextcol < columnCount() 
+       bool colright = columnRightLine(c);
+       bool colleft = columnLeftLine(c);
+       bool nextcolleft = nextcol < column_info.size() && columnLeftLine(nextcol);
+       bool nextcellleft = nextcol < column_info.size() 
                && leftLine(cellIndex(r, nextcol));
+       bool coldouble = colright && nextcolleft;
        bool celldouble = rightLine(cell) && nextcellleft;
-       bool doubleright = celldouble && (isMultiColumn(cell) || !coldouble);
        ismulticol = isMultiColumn(cell) 
-               || (leftLine(cell) && !columnLeftLine(c))
-               || (rightLine(cell) && !columnRightLine(c))
-               || (!celldouble && coldouble) || doubleright || forceleft;
+               || (c == 0 && colleft != leftLine(cell))
+               || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
+               || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
+               || (coldouble != celldouble);
        if (ismulticol) {
                os << "\\multicolumn{" << columnSpan(cell) << "}{";
-               if (leftLine(cell) || forceleft)
+               if (c ==0 && leftLine(cell))
                        os << '|';
                if (!cellInfo(cell).align_special.empty()) {
                        os << cellInfo(cell).align_special;
                } else {
                        if (!getPWidth(cell).zero()) {
+                               switch (align) {
+                               case LYX_ALIGN_LEFT:
+                                       os << ">{\\raggedright}";
+                                       break;
+                               case LYX_ALIGN_RIGHT:
+                                       os << ">{\\raggedleft}";
+                                       break;
+                               case LYX_ALIGN_CENTER:
+                                       os << ">{\\centering}";
+                                       break;
+                               default:
+                                       break;
+                               }
                                switch (valign) {
                                case LYX_VALIGN_TOP:
                                        os << 'p';
@@ -1922,9 +2010,9 @@ int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol)
                                }
                        } // end if else !getPWidth
                } // end if else !cellinfo_of_cell
-               if (rightLine(cell))
+               if (rightLine(cell) || nextcellleft)
                        os << '|';
-               if (doubleright)
+               if (celldouble)
                        // add extra vertical line if we want a double one
                        os << '|';
                os << "}{";
@@ -1972,6 +2060,9 @@ int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol)
 int Tabular::TeXCellPostamble(odocstream & os, idx_type cell, bool ismulticol) const
 {
        int ret = 0;
+       row_type const r = cellRow(cell);
+       if (is_long_tabular && row_info[r].caption)
+               return ret;
 
        // usual cells
        if (getUsebox(cell) == BOX_PARBOX)
@@ -1998,44 +2089,55 @@ int Tabular::TeXLongtableHeaderFooter(odocstream & os,
                return 0;
 
        int ret = 0;
-       // output header info
-       if (haveLTHead()) {
-               if (endhead.topDL) {
+       // caption handling
+       // the caption must be output befrore the headers
+       if (haveLTCaption()) {
+               for (row_type i = 0; i < row_info.size(); ++i) {
+                       if (row_info[i].caption) {
+                               ret += TeXRow(os, i, runparams);
+                       }
+               }
+       }
+       // output first header info
+       // first header must be output before the header, otherwise the
+       // correct caption placement becomes really wierd
+       if (haveLTFirstHead()) {
+               if (endfirsthead.topDL) {
                        os << "\\hline\n";
                        ++ret;
                }
-               for (row_type i = 0; i < rowCount(); ++i) {
-                       if (row_info[i].endhead) {
+               for (row_type i = 0; i < row_info.size(); ++i) {
+                       if (row_info[i].endfirsthead) {
                                ret += TeXRow(os, i, runparams);
                        }
                }
-               if (endhead.bottomDL) {
+               if (endfirsthead.bottomDL) {
                        os << "\\hline\n";
                        ++ret;
                }
-               os << "\\endhead\n";
+               os << "\\endfirsthead\n";
                ++ret;
-               if (endfirsthead.empty) {
+       }
+       // output header info
+       if (haveLTHead()) {
+               if (!haveLTFirstHead()) {
                        os << "\\endfirsthead\n";
                        ++ret;
                }
-       }
-       // output firstheader info
-       if (haveLTFirstHead()) {
-               if (endfirsthead.topDL) {
+               if (endhead.topDL) {
                        os << "\\hline\n";
                        ++ret;
                }
-               for (row_type i = 0; i < rowCount(); ++i) {
-                       if (row_info[i].endfirsthead) {
+               for (row_type i = 0; i < row_info.size(); ++i) {
+                       if (row_info[i].endhead) {
                                ret += TeXRow(os, i, runparams);
                        }
                }
-               if (endfirsthead.bottomDL) {
+               if (endhead.bottomDL) {
                        os << "\\hline\n";
                        ++ret;
                }
-               os << "\\endfirsthead\n";
+               os << "\\endhead\n";
                ++ret;
        }
        // output footer info
@@ -2044,7 +2146,7 @@ int Tabular::TeXLongtableHeaderFooter(odocstream & os,
                        os << "\\hline\n";
                        ++ret;
                }
-               for (row_type i = 0; i < rowCount(); ++i) {
+               for (row_type i = 0; i < row_info.size(); ++i) {
                        if (row_info[i].endfoot) {
                                ret += TeXRow(os, i, runparams);
                        }
@@ -2055,7 +2157,7 @@ int Tabular::TeXLongtableHeaderFooter(odocstream & os,
                }
                os << "\\endfoot\n";
                ++ret;
-               if (endlastfoot.empty) {
+               if (!haveLTLastFoot()) {
                        os << "\\endlastfoot\n";
                        ++ret;
                }
@@ -2066,7 +2168,7 @@ int Tabular::TeXLongtableHeaderFooter(odocstream & os,
                        os << "\\hline\n";
                        ++ret;
                }
-               for (row_type i = 0; i < rowCount(); ++i) {
+               for (row_type i = 0; i < row_info.size(); ++i) {
                        if (row_info[i].endlastfoot) {
                                ret += TeXRow(os, i, runparams);
                        }
@@ -2086,8 +2188,9 @@ bool Tabular::isValidRow(row_type row) const
 {
        if (!is_long_tabular)
                return true;
-       return !row_info[row].endhead && !row_info[row].endfirsthead &&
-                       !row_info[row].endfoot && !row_info[row].endlastfoot;
+       return !row_info[row].endhead && !row_info[row].endfirsthead
+               && !row_info[row].endfoot && !row_info[row].endlastfoot
+               && !row_info[row].caption;
 }
 
 
@@ -2095,7 +2198,13 @@ int Tabular::TeXRow(odocstream & os, row_type i,
                       OutputParams const & runparams) const
 {
        idx_type cell = cellIndex(i, 0);
-       int ret = TeXTopHLine(os, i);
+       shared_ptr<InsetTableCell> inset = cellInset(cell);
+       Paragraph const & par = inset->paragraphs().front();
+       string const lang = par.getParLanguage(buffer().params())->lang();
+
+       //output the top line
+       int ret = TeXTopHLine(os, i, lang);
+
        if (row_info[i].top_space_default) {
                if (use_booktabs)
                        os << "\\addlinespace\n";
@@ -2115,7 +2224,7 @@ int Tabular::TeXRow(odocstream & os, row_type i,
                ++ret;
        }
        bool ismulticol = false;
-       for (col_type j = 0; j < columnCount(); ++j) {
+       for (col_type j = 0; j < column_info.size(); ++j) {
                if (isPartOfMultiColumn(i, j))
                        continue;
                ret += TeXCellPreamble(os, cell, ismulticol);
@@ -2127,16 +2236,26 @@ int Tabular::TeXRow(odocstream & os, row_type i,
                        && getPWidth(cell).zero();
 
                if (rtl) {
-                       if (par.getParLanguage(buffer().params())->lang() ==
-                       "farsi")
+                       string const lang =
+                               par.getParLanguage(buffer().params())->lang();
+                       if (lang == "farsi")
                                os << "\\textFR{";
-                       else if (par.getParLanguage(buffer().params())->lang() == "arabic_arabi")
+                       else if (lang == "arabic_arabi")
                                os << "\\textAR{";
-                       // currently, remaning RTL languages are arabic_arabtex and hebrew
+                       // currently, remaning RTL languages are
+                       // arabic_arabtex and hebrew
                        else
                                os << "\\R{";
                }
-               ret += inset->latex(os, runparams);
+               // pass to the OutputParams that we are in a cell and
+               // which alignment we have set.
+               // InsetNewline needs this context information.
+               OutputParams newrp(runparams);
+               newrp.inTableCell = (getAlignment(cell) == LYX_ALIGN_BLOCK)
+                                   ? OutputParams::PLAIN
+                                   : OutputParams::ALIGNED;
+               ret += inset->latex(os, newrp);
+               runparams.encoding = newrp.encoding;
                if (rtl)
                        os << '}';
 
@@ -2161,7 +2280,10 @@ int Tabular::TeXRow(odocstream & os, row_type i,
        }
        os << '\n';
        ++ret;
-       ret += TeXBottomHLine(os, i);
+
+       //output the bottom line
+       ret += TeXBottomHLine(os, i, lang);
+
        if (row_info[i].interline_space_default) {
                if (use_booktabs)
                        os << "\\addlinespace\n";
@@ -2196,12 +2318,25 @@ int Tabular::latex(odocstream & os, OutputParams const & runparams) const
                ++ret;
        }
        if (is_long_tabular)
-               os << "\\begin{longtable}{";
+               os << "\\begin{longtable}";
        else
-               os << "\\begin{tabular}{";
+               os << "\\begin{tabular}";
 
-       for (col_type i = 0; i < columnCount(); ++i) {
-               if (!use_booktabs && columnLeftLine(i))
+       switch (tabular_valignment) {
+               case LYX_VALIGN_TOP:
+                       os << "[t]";
+                       break;
+               case LYX_VALIGN_BOTTOM:
+                       os << "[b]";
+                       break;
+               case LYX_VALIGN_MIDDLE:
+                       break;
+       }
+       
+       os << "{";
+
+       for (col_type i = 0; i < column_info.size(); ++i) {
+               if (columnLeftLine(i))
                        os << '|';
                if (!column_info[i].align_special.empty()) {
                        os << column_info[i].align_special;
@@ -2252,7 +2387,7 @@ int Tabular::latex(odocstream & os, OutputParams const & runparams) const
                                }
                        } // end if else !column_info[i].p_width
                } // end if else !column_info[i].align_special
-               if (!use_booktabs && columnRightLine(i))
+               if (columnRightLine(i))
                        os << '|';
        }
        os << "}\n";
@@ -2264,7 +2399,7 @@ int Tabular::latex(odocstream & os, OutputParams const & runparams) const
        //+                      the single row and columns (cells)            +
        //+---------------------------------------------------------------------
 
-       for (row_type i = 0; i < rowCount(); ++i) {
+       for (row_type i = 0; i < row_info.size(); ++i) {
                if (isValidRow(i)) {
                        ret += TeXRow(os, i, runparams);
                        if (is_long_tabular && row_info[i].newpage) {
@@ -2298,7 +2433,7 @@ int Tabular::docbookRow(odocstream & os, row_type row,
        idx_type cell = getFirstCellInRow(row);
 
        os << "<row>\n";
-       for (col_type j = 0; j < columnCount(); ++j) {
+       for (col_type j = 0; j < column_info.size(); ++j) {
                if (isPartOfMultiColumn(row, j))
                        continue;
 
@@ -2351,10 +2486,10 @@ int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
        //+                      first the opening preamble                    +
        //+---------------------------------------------------------------------
 
-       os << "<tgroup cols=\"" << columnCount()
+       os << "<tgroup cols=\"" << column_info.size()
           << "\" colsep=\"1\" rowsep=\"1\">\n";
 
-       for (col_type i = 0; i < columnCount(); ++i) {
+       for (col_type i = 0; i < column_info.size(); ++i) {
                os << "<colspec colname=\"col" << i << "\" align=\"";
                switch (column_info[i].alignment) {
                case LYX_ALIGN_LEFT:
@@ -2379,11 +2514,12 @@ int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
        //+---------------------------------------------------------------------
 
        // output header info
-       if (haveLTHead() || haveLTFirstHead()) {
+       if (haveLTHead() || haveLTFirstHead()|| haveLTCaption()) {
                os << "<thead>\n";
                ++ret;
-               for (row_type i = 0; i < rowCount(); ++i) {
-                       if (row_info[i].endhead || row_info[i].endfirsthead) {
+               for (row_type i = 0; i < row_info.size(); ++i) {
+                       if (row_info[i].endhead || row_info[i].endfirsthead
+                               || row_info[i].caption) {
                                ret += docbookRow(os, i, runparams);
                        }
                }
@@ -2394,7 +2530,7 @@ int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
        if (haveLTFoot() || haveLTLastFoot()) {
                os << "<tfoot>\n";
                ++ret;
-               for (row_type i = 0; i < rowCount(); ++i) {
+               for (row_type i = 0; i < row_info.size(); ++i) {
                        if (row_info[i].endfoot || row_info[i].endlastfoot) {
                                ret += docbookRow(os, i, runparams);
                        }
@@ -2409,7 +2545,7 @@ int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
 
        os << "<tbody>\n";
        ++ret;
-       for (row_type i = 0; i < rowCount(); ++i) {
+       for (row_type i = 0; i < row_info.size(); ++i) {
                if (isValidRow(i)) {
                        ret += docbookRow(os, i, runparams);
                }
@@ -2457,7 +2593,7 @@ bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
                }
                col_type column = cellColumn(i);
                int len = clen[column];
-               while (column < columnCount() - 1
+               while (column < column_info.size() - 1
                       && isPartOfMultiColumn(row, ++column))
                        len += clen[column] + 4;
                os << docstring(len, ch);
@@ -2505,7 +2641,7 @@ bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
                }
                col_type column = cellColumn(i);
                int len = clen[column];
-               while (column < columnCount() -1
+               while (column < column_info.size() -1
                       && isPartOfMultiColumn(row, ++column))
                        len += clen[column] + 4;
                os << docstring(len, ch);
@@ -2544,7 +2680,7 @@ void Tabular::plaintextPrintCell(odocstream & os,
 
        unsigned int len1 = sstr.str().length();
        unsigned int len2 = clen[column];
-       while (column < columnCount() -1
+       while (column < column_info.size() -1
               && isPartOfMultiColumn(row, ++column))
                len2 += clen[column] + 4;
        len2 -= len1;
@@ -2579,13 +2715,13 @@ void Tabular::plaintext(odocstream & os,
                           bool onlydata, char_type delim) const
 {
        // first calculate the width of the single columns
-       vector<unsigned int> clen(columnCount());
+       vector<unsigned int> clen(column_info.size());
 
        if (!onlydata) {
                // first all non (real) multicolumn cells!
-               for (col_type j = 0; j < columnCount(); ++j) {
+               for (col_type j = 0; j < column_info.size(); ++j) {
                        clen[j] = 0;
-                       for (row_type i = 0; i < rowCount(); ++i) {
+                       for (row_type i = 0; i < row_info.size(); ++i) {
                                idx_type cell = cellIndex(i, j);
                                if (isMultiColumnReal(cell))
                                        continue;
@@ -2596,8 +2732,8 @@ void Tabular::plaintext(odocstream & os,
                        }
                }
                // then all (real) multicolumn cells!
-               for (col_type j = 0; j < columnCount(); ++j) {
-                       for (row_type i = 0; i < rowCount(); ++i) {
+               for (col_type j = 0; j < column_info.size(); ++j) {
+                       for (row_type i = 0; i < row_info.size(); ++i) {
                                idx_type cell = cellIndex(i, j);
                                if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
                                        continue;
@@ -2613,10 +2749,10 @@ void Tabular::plaintext(odocstream & os,
                }
        }
        idx_type cell = 0;
-       for (row_type i = 0; i < rowCount(); ++i) {
+       for (row_type i = 0; i < row_info.size(); ++i) {
                if (!onlydata && plaintextTopHLine(os, i, clen))
                        os << docstring(depth * 2, ' ');
-               for (col_type j = 0; j < columnCount(); ++j) {
+               for (col_type j = 0; j < column_info.size(); ++j) {
                        if (isPartOfMultiColumn(i, j))
                                continue;
                        if (onlydata && j > 0)
@@ -2654,49 +2790,21 @@ void Tabular::setCellInset(row_type row, col_type column,
 {
        CellData & cd = cell_info[row][column];
        cd.inset = ins;
-       // reset the InsetTableCell's pointers
-       ins->setCellData(&cd);
-       ins->setTabular(this);
-}
-
-
-Tabular::idx_type
-Tabular::cellFromInset(Inset const * inset) const
-{
-       // is this inset part of the tabular?
-       if (!inset) {
-               lyxerr << "Error: this is not a cell of the tabular!" << endl;
-               BOOST_ASSERT(false);
-       }
-
-       for (idx_type cell = 0, n = cellCount(); cell < n; ++cell)
-               if (cellInset(cell).get() == inset) {
-                       LYXERR(Debug::INSETTEXT, "Tabular::cellFromInset: "
-                               << "cell=" << cell);
-                       return cell;
-               }
-
-       // We should have found a cell at this point
-       lyxerr << "Tabular::cellFromInset: Cell of inset "
-               << inset << " not found!" << endl;
-       BOOST_ASSERT(false);
-       // shut up compiler
-       return 0;
 }
 
 
 void Tabular::validate(LaTeXFeatures & features) const
 {
        features.require("NeedTabularnewline");
-       if (useBookTabs())
+       if (use_booktabs)
                features.require("booktabs");
-       if (isLongTabular())
+       if (is_long_tabular)
                features.require("longtable");
        if (needRotating())
                features.require("rotating");
-       for (idx_type cell = 0; cell < cellCount(); ++cell) {
-               if (getVAlignment(cell) != LYX_VALIGN_TOP ||
-                    (!getPWidth(cell).zero() && !isMultiColumn(cell)))
+       for (idx_type cell = 0; cell < numberofcells; ++cell) {
+               if (getVAlignment(cell) != LYX_VALIGN_TOP
+                   || !getPWidth(cell).zero())
                        features.require("array");
                cellInset(cell)->validate(features);
        }
@@ -2724,33 +2832,31 @@ Tabular::BoxType Tabular::useParbox(idx_type cell) const
 //
 /////////////////////////////////////////////////////////////////////
 
-InsetTableCell::InsetTableCell(Buffer const & buf,
-       Tabular::CellData const * cell, Tabular const * table)
-       : InsetText(buf), cell_data_(cell), table_(table)
+InsetTableCell::InsetTableCell(Buffer & buf)
+       : InsetText(buf), isFixedWidth(false),
+         contentAlign(LYX_ALIGN_CENTER)
 {}
 
 
-bool InsetTableCell::forceEmptyLayout(idx_type) const
+bool InsetTableCell::forcePlainLayout(idx_type) const
 {
-       BOOST_ASSERT(table_);
-       BOOST_ASSERT(cell_data_);
-       return table_->getPWidth(cell_data_->cellno).zero();
+       return !isFixedWidth;
 }
 
+
 bool InsetTableCell::allowParagraphCustomization(idx_type) const
 {
-       BOOST_ASSERT(table_);
-       BOOST_ASSERT(cell_data_);
-       return !table_->getPWidth(cell_data_->cellno).zero();
+       return isFixedWidth;
 }
 
+
 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
        FuncStatus & status) const
 {
        bool enabled;
        switch (cmd.action) {
        case LFUN_LAYOUT:
-               enabled = !forceEmptyLayout();
+               enabled = !forcePlainLayout();
                break;
        case LFUN_LAYOUT_PARAGRAPH:
                enabled = allowParagraphCustomization();
@@ -2758,29 +2864,48 @@ bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
        default:
                return InsetText::getStatus(cur, cmd, status);
        }
-       status.enabled(enabled);
+       status.setEnabled(enabled);
        return true;
 }
 
+docstring InsetTableCell::asString(bool intoInsets) 
+{
+       docstring retval;
+       if (paragraphs().empty())
+               return retval;
+       ParagraphList::const_iterator it = paragraphs().begin();
+       ParagraphList::const_iterator en = paragraphs().end();
+       bool first = true;
+       for (; it != en; ++it) {
+               if (!first)
+                       retval += "\n";
+               else
+                       first = false;
+               retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
+       }
+       return retval;
+}
+
+
+
 /////////////////////////////////////////////////////////////////////
 //
 // InsetTabular
 //
 /////////////////////////////////////////////////////////////////////
 
-InsetTabular::InsetTabular(Buffer const & buf, row_type rows,
+InsetTabular::InsetTabular(Buffer & buf, row_type rows,
                           col_type columns)
        : tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
        rowselect_(false), colselect_(false)
 {
-       setBuffer(const_cast<Buffer &>(buf)); // FIXME: remove later
+       setBuffer(buf); // FIXME: remove later
 }
 
 
 InsetTabular::InsetTabular(InsetTabular const & tab)
        : Inset(tab), tabular(tab.tabular),  scx_(0)
 {
-       setBuffer(const_cast<Buffer &>(tab.buffer())); // FIXME: remove later
 }
 
 
@@ -2790,6 +2915,13 @@ InsetTabular::~InsetTabular()
 }
 
 
+void InsetTabular::setBuffer(Buffer & buf)
+{
+       tabular.setBuffer(buf);
+       Inset::setBuffer(buf);
+}
+
+
 bool InsetTabular::insetAllowed(InsetCode code) const
 {
        if (code == MATHMACRO_CODE)
@@ -2837,7 +2969,7 @@ int InsetTabular::rowFromY(Cursor & cur, int y) const
 {
        // top y coordinate of tabular
        int h = yo(cur.bv()) - tabular.rowAscent(0);
-       size_t nrows = tabular.rowCount();
+       size_t nrows = tabular.row_info.size();
        row_type r = 0;
        for (; r < nrows && y > h; ++r) {
                h += tabular.rowAscent(r);
@@ -2852,7 +2984,7 @@ int InsetTabular::columnFromX(Cursor & cur, int x) const
 {
        // left x coordinate of tabular
        int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
-       size_t ncols = tabular.columnCount();
+       size_t ncols = tabular.column_info.size();
        col_type c = 0;
        for (; c < ncols && x > w; ++c)
                w += tabular.columnWidth(c);
@@ -2866,14 +2998,14 @@ void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
        //      mi.base.textwidth << "\n";
        if (!mi.base.bv) {
                LYXERR0("need bv");
-               BOOST_ASSERT(false);
+               LASSERT(false, /**/);
        }
 
        row_type i = 0;
-       for (idx_type cell = 0; i < tabular.rowCount(); ++i) {
+       for (idx_type cell = 0; i < tabular.row_info.size(); ++i) {
                int maxAsc = 0;
                int maxDesc = 0;
-               for (col_type j = 0; j < tabular.columnCount(); ++j) {
+               for (col_type j = 0; j < tabular.column_info.size(); ++j) {
                        if (tabular.isPartOfMultiColumn(i, j))
                                // Multicolumn cell, but not first one
                                continue;
@@ -2910,11 +3042,38 @@ void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
        dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
 }
 
+bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
+       const
+{
+       if (&cur.inset() == this && cur.selection()) {
+               if (cur.selIsMultiCell()) {
+                       row_type rs, re;
+                       col_type cs, ce;
+                       getSelection(cur, rs, re, cs, ce);
+                       
+                       if (col >= cs && col <= ce && row >= rs && row <= re)
+                               return true;
+               } else 
+                       if (col == tabular.cellColumn(cur.idx()) 
+                               && row == tabular.cellRow(cur.idx())) {
+                       CursorSlice const & beg = cur.selBegin();
+                       CursorSlice const & end = cur.selEnd();
+
+                       if ((end.lastpos() > 0 || end.lastpit() > 0)
+                                 && end.pos() == end.lastpos() && beg.pos() == 0
+                                 && end.pit() == end.lastpit() && beg.pit() == 0)
+                               return true;
+               }
+       }
+       return false;
+}
+
 
 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
 {
        //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
        BufferView * bv = pi.base.bv;
+       Cursor & cur = pi.base.bv->cursor();
 
        // FIXME: As the full backrgound is painted in drawSelection(),
        // we have no choice but to do a full repaint for the Text cells.
@@ -2926,20 +3085,22 @@ void InsetTabular::draw(PainterInfo & pi, int x, int y) const
        x += ADD_TO_TABULAR_WIDTH;
 
        bool const original_drawing_state = pi.pain.isDrawingEnabled();
+       bool const original_selection_state = pi.selected;
 
        idx_type idx = 0;
        first_visible_cell = Tabular::npos;
-       for (row_type i = 0; i < tabular.rowCount(); ++i) {
+       for (row_type i = 0; i < tabular.row_info.size(); ++i) {
                int nx = x;
                int const a = tabular.rowAscent(i);
                int const d = tabular.rowDescent(i);
                idx = tabular.cellIndex(i, 0);
-               for (col_type j = 0; j < tabular.columnCount(); ++j) {
+               for (col_type j = 0; j < tabular.column_info.size(); ++j) {
                        if (tabular.isPartOfMultiColumn(i, j))
                                continue;
                        if (first_visible_cell == Tabular::npos)
                                first_visible_cell = idx;
 
+                       pi.selected |= isCellSelected(cur, i, j);
                        int const cx = nx + tabular.getBeginningOfTextInCell(idx);
                        // Cache the Inset position.
                        bv->coordCache().insets().add(cell(idx).get(), cx, y);
@@ -2949,17 +3110,18 @@ void InsetTabular::draw(PainterInfo & pi, int x, int y) const
                            || y - a > bv->workHeight()) {
                                pi.pain.setDrawingEnabled(false);
                                cell(idx)->draw(pi, cx, y);
-                               drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
+                               drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
                                pi.pain.setDrawingEnabled(original_drawing_state);
                        } else {
                                cell(idx)->draw(pi, cx, y);
-                               drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
+                               drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
                        }
                        nx += tabular.columnWidth(idx);
                        ++idx;
+                       pi.selected = original_selection_state;
                }
 
-               if (i + 1 < tabular.rowCount())
+               if (i + 1 < tabular.row_info.size())
                        y += d + tabular.rowAscent(i + 1) +
                                tabular.getAdditionalHeight(i + 1);
        }
@@ -2969,6 +3131,7 @@ void InsetTabular::draw(PainterInfo & pi, int x, int y) const
 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
 {
        Cursor & cur = pi.base.bv->cursor();
+       resetPos(cur);
 
        x += scx_ + ADD_TO_TABULAR_WIDTH;
 
@@ -2979,7 +3142,7 @@ void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
        int const w = tabular.width();
        int const h = tabular.height();
        int yy = y - tabular.rowAscent(0);
-       pi.pain.fillRectangle(x, yy, w, h, backgroundColor());
+       pi.pain.fillRectangle(x, yy, w, h, pi.backgroundColor(this));
 
        if (!cur.selection())
                return;
@@ -2988,26 +3151,24 @@ void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
 
        //resetPos(cur);
 
+       bool const full_cell_selected = isCellSelected(cur,
+               tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
 
-       if (tablemode(cur)) {
-               row_type rs, re;
-               col_type cs, ce;
-               getSelection(cur, rs, re, cs, ce);
+       if (cur.selIsMultiCell() || full_cell_selected) {
                y -= tabular.rowAscent(0);
-               for (row_type j = 0; j < tabular.rowCount(); ++j) {
+               for (row_type j = 0; j < tabular.row_info.size(); ++j) {
                        int const a = tabular.rowAscent(j);
                        int const h = a + tabular.rowDescent(j);
                        int xx = x;
                        y += tabular.getAdditionalHeight(j);
-                       for (col_type i = 0; i < tabular.columnCount(); ++i) {
+                       for (col_type i = 0; i < tabular.column_info.size(); ++i) {
                                if (tabular.isPartOfMultiColumn(j, i))
                                        continue;
                                idx_type const cell =
                                        tabular.cellIndex(j, i);
                                int const w = tabular.columnWidth(cell);
-                               if (i >= cs && i <= ce && j >= rs && j <= re)
-                                       pi.pain.fillRectangle(xx, y, w, h,
-                                                             Color_selection);
+                               if (isCellSelected(cur, j, i))
+                                       pi.pain.fillRectangle(xx, y, w, h, Color_selection);
                                xx += w;
                        }
                        y += h;
@@ -3022,16 +3183,16 @@ void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
 
 
 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
-                                row_type row, idx_type cell, bool erased) const
+                                row_type row, idx_type cell, Change const & change) const
 {
        int x2 = x + tabular.columnWidth(cell);
        bool on_off = false;
-       ColorCode col = Color_tabularline;
-       ColorCode onoffcol = Color_tabularonoffline;
+       Color col = Color_tabularline;
+       Color onoffcol = Color_tabularonoffline;
 
-       if (erased) {
-               col = Color_deletedtext;
-               onoffcol = Color_deletedtext;
+       if (change.changed()) {
+               col = change.color();
+               onoffcol = change.color();
        }
 
        if (!tabular.topAlreadyDrawn(cell)) {
@@ -3073,7 +3234,7 @@ void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
 {
        //lyxerr << "InsetTabular::edit: " << this << endl;
        cur.finishUndo();
-       cur.selection() = false;
+       cur.setSelection(false);
        cur.push(*this);
        if (front) {
                if (isRightToLeft(cur))
@@ -3084,9 +3245,9 @@ void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
                cur.pos() = 0;
        } else {
                if (isRightToLeft(cur))
-                       cur.idx() = tabular.getFirstCellInRow(tabular.rowCount() - 1);
+                       cur.idx() = tabular.getFirstCellInRow(tabular.row_info.size() - 1);
                else
-                       cur.idx() = tabular.cellCount() - 1;
+                       cur.idx() = tabular.numberofcells - 1;
                cur.pit() = 0;
                cur.pos() = cur.lastpos(); // FIXME crude guess
        }
@@ -3099,19 +3260,19 @@ void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
 void InsetTabular::updateLabels(ParIterator const & it)
 {
        // In a longtable, tell captions what the current float is
-       Counters & cnts = buffer().params().documentClass().counters();
+       Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
        string const saveflt = cnts.current_float();
-       if (tabular.isLongTabular())
+       if (tabular.is_long_tabular)
                cnts.current_float("table");
 
        ParIterator it2 = it;
        it2.forwardPos();
        size_t const end = it2.nargs();
        for ( ; it2.idx() < end; it2.top().forwardIdx())
-               lyx::updateLabels(buffer(), it2);
+               buffer().updateLabels(it2);
 
        //reset afterwards
-       if (tabular.isLongTabular())
+       if (tabular.is_long_tabular)
                cnts.current_float(saveflt);
 }
 
@@ -3136,7 +3297,7 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                        cur.resetAnchor();
                        cur.idx() = tabular.getLastCellInRow(r);
                        cur.pos() = cur.lastpos();
-                       cur.selection() = true;
+                       cur.setSelection(true);
                        bvcur = cur; 
                        rowselect_ = true;
                        break;
@@ -3149,9 +3310,9 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                        cur.idx() = tabular.cellIndex(0, c);
                        cur.pos() = 0;
                        cur.resetAnchor();
-                       cur.idx() = tabular.cellIndex(tabular.rowCount() - 1, c);
+                       cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
                        cur.pos() = cur.lastpos();
-                       cur.selection() = true;
+                       cur.setSelection(true);
                        bvcur = cur; 
                        colselect_ = true;
                        break;
@@ -3160,7 +3321,7 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                // some cells (bug 2715).
                if (cmd.button() == mouse_button::button3
                    && &bvcur.selBegin().inset() == this 
-                   && tablemode(bvcur)) 
+                   && bvcur.selIsMultiCell()) 
                        ;
                else
                        // Let InsetTableCell do it
@@ -3179,16 +3340,24 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                        if (rowselect_) {
                                row_type r = rowFromY(cur, cmd.y);
                                cur.idx() = tabular.getLastCellInRow(r);
+                               // we need to reset the cursor's pit and pos now, as the old ones
+                               // may no longer be valid.
+                               cur.pit() = 0;
+                               cur.pos() = 0;
                                bvcur.setCursor(cur);
-                               bvcur.selection() = true;
+                               bvcur.setSelection(true);
                                break;
                        }
                        // select (additional) column
                        if (colselect_) {
                                col_type c = columnFromX(cur, cmd.x);
-                               cur.idx() = tabular.cellIndex(tabular.rowCount() - 1, c);
+                               cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
+                               // we need to reset the cursor's pit and pos now, as the old ones
+                               // may no longer be valid.
+                               cur.pit() = 0;
+                               cur.pos() = 0;
                                bvcur.setCursor(cur);
-                               bvcur.selection() = true;
+                               bvcur.setSelection(true);
                                break;
                        }
                        // only update if selection changes
@@ -3197,7 +3366,13 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                                cur.noUpdate();
                        setCursorFromCoordinates(cur, cmd.x, cmd.y);
                        bvcur.setCursor(cur);
-                       bvcur.selection() = true;
+                       bvcur.setSelection(true);
+                       // if this is a multicell selection, we just set the cursor to
+                       // the beginning of the cell's text.
+                       if (bvcur.selIsMultiCell()) {
+                               bvcur.pit() = bvcur.lastpit();
+                               bvcur.pos() = bvcur.lastpos();
+                       }
                }
                break;
 
@@ -3208,94 +3383,149 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
 
        case LFUN_CELL_BACKWARD:
                movePrevCell(cur);
-               cur.selection() = false;
+               cur.setSelection(false);
                break;
 
        case LFUN_CELL_FORWARD:
                moveNextCell(cur);
-               cur.selection() = false;
+               cur.setSelection(false);
                break;
+
        case LFUN_CHAR_FORWARD_SELECT:
        case LFUN_CHAR_FORWARD:
-               cell(cur.idx())->dispatch(cur, cmd);
-               if (!cur.result().dispatched()) {
-                       moveNextCell(cur);
-                       if (sl == cur.top())
-                               cmd = FuncRequest(LFUN_FINISHED_FORWARD);
-                       else
-                               cur.dispatched();
-               }
-               break;
-
        case LFUN_CHAR_BACKWARD_SELECT:
        case LFUN_CHAR_BACKWARD:
-               cell(cur.idx())->dispatch(cur, cmd);
-               if (!cur.result().dispatched()) {
-                       movePrevCell(cur);
-                       if (sl == cur.top())
-                               cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
-                       else
+       case LFUN_CHAR_RIGHT_SELECT:
+       case LFUN_CHAR_RIGHT:
+       case LFUN_CHAR_LEFT_SELECT:
+       case LFUN_CHAR_LEFT: {
+               // determine whether we move to next or previous cell, where to enter 
+               // the new cell from, and which command to "finish" (i.e., exit the
+               // inset) with:
+               bool next_cell;
+               EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
+               FuncCode finish_lfun;
+
+               if (cmd.action == LFUN_CHAR_FORWARD 
+                               || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
+                       next_cell = true;
+                       finish_lfun = LFUN_FINISHED_FORWARD;
+               }
+               else if (cmd.action == LFUN_CHAR_BACKWARD
+                               || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
+                       next_cell = false;
+                       finish_lfun = LFUN_FINISHED_BACKWARD;
+               }
+               // LEFT or RIGHT commands --- the interpretation will depend on the 
+               // table's direction.
+               else {
+                       bool const right = cmd.action == LFUN_CHAR_RIGHT
+                               || cmd.action == LFUN_CHAR_RIGHT_SELECT;
+                       next_cell = isRightToLeft(cur) != right;
+                       
+                       if (lyxrc.visual_cursor)
+                               entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
+
+                       finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
+               }
+
+               bool const select = cmd.action == LFUN_CHAR_FORWARD_SELECT ||
+                   cmd.action == LFUN_CHAR_BACKWARD_SELECT ||
+                   cmd.action == LFUN_CHAR_RIGHT_SELECT ||
+                   cmd.action == LFUN_CHAR_LEFT_SELECT;
+
+               // If we have a multicell selection or we're 
+               // not doing some LFUN_*_SELECT thing anyway...
+               if (!cur.selIsMultiCell() || !select) {
+                       col_type const c = tabular.cellColumn(cur.idx());
+                       row_type const r = tabular.cellRow(cur.idx());
+                       // Are we trying to select the whole cell and is the whole cell 
+                       // not yet selected?
+                       bool const select_whole = select && !isCellSelected(cur, r, c) &&
+                               ((next_cell && cur.pit() == cur.lastpit() 
+                               && cur.pos() == cur.lastpos())
+                               || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
+
+                       // ...try to dispatch to the cell's inset.
+                       cell(cur.idx())->dispatch(cur, cmd);
+
+                       bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
+                       
+                       // When we already have a selection we want to select the whole cell
+                       // before going to the next cell.
+                       if (select_whole && !empty_cell){
+                               getText(cur.idx())->selectAll(cur);
                                cur.dispatched();
+                               break;
+                       }
+
+                       // FIXME: When we support the selection of an empty cell, remove 
+                       // the !empty_cell from this condition. For now we jump to the next
+                       // cell if the current cell is empty.
+                       if (cur.result().dispatched() && !empty_cell)
+                               break;
                }
-               break;
 
-       case LFUN_CHAR_RIGHT_SELECT:
-       case LFUN_CHAR_RIGHT:
-               //FIXME: for visual cursor, really move right
-               if (isRightToLeft(cur))
-                       lyx::dispatch(FuncRequest(
-                               cmd.action == LFUN_CHAR_RIGHT_SELECT ?
-                                       LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD));
+               // move to next/prev cell, as appropriate
+               // note that we will always do this if we're selecting and we have
+               // a multicell selection
+               LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
+                       << " cell from: " << int(entry_from));
+               if (next_cell)
+                       moveNextCell(cur, entry_from);
                else
-                       lyx::dispatch(FuncRequest(
-                               cmd.action == LFUN_CHAR_RIGHT_SELECT ?
-                                       LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD));
-               break;
-
-       case LFUN_CHAR_LEFT_SELECT:
-       case LFUN_CHAR_LEFT:
-               //FIXME: for visual cursor, really move left
-               if (isRightToLeft(cur))
-                       lyx::dispatch(FuncRequest(
-                               cmd.action == LFUN_CHAR_LEFT_SELECT ?
-                                       LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD));
+                       movePrevCell(cur, entry_from);
+               // if we're exiting the table, call the appropriate FINISHED lfun
+               if (sl == cur.top())
+                       cmd = FuncRequest(finish_lfun);
                else
-                       lyx::dispatch(FuncRequest(
-                               cmd.action == LFUN_CHAR_LEFT_SELECT ?
-                                       LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD));
+                       cur.dispatched();
                break;
 
+       }
+
        case LFUN_DOWN_SELECT:
        case LFUN_DOWN:
-               cell(cur.idx())->dispatch(cur, cmd);
+               if (!(cur.selection() && cur.selIsMultiCell()))
+                       cell(cur.idx())->dispatch(cur, cmd);
+               
                cur.dispatched(); // override the cell's decision
-               if (sl == cur.top())
+               if (sl == cur.top()) {
                        // if our Text didn't do anything to the cursor
                        // then we try to put the cursor into the cell below
                        // setting also the right targetX.
-                       if (tabular.cellRow(cur.idx()) != tabular.rowCount() - 1) {
+                       cur.selHandle(cmd.action == LFUN_DOWN_SELECT);
+                       if (tabular.cellRow(cur.idx()) != tabular.row_info.size() - 1) {
                                cur.idx() = tabular.cellBelow(cur.idx());
                                cur.pit() = 0;
                                TextMetrics const & tm =
                                        cur.bv().textMetrics(cell(cur.idx())->getText(0));
                                cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
                        }
+               }
                if (sl == cur.top()) {
                        // we trick it to go to forward after leaving the
                        // tabular.
                        cmd = FuncRequest(LFUN_FINISHED_FORWARD);
                        cur.undispatched();
                }
+               if (cur.selIsMultiCell()) {
+                       cur.pit() = cur.lastpit();
+                       cur.pos() = cur.lastpos();
+                       return;
+               }
                break;
 
        case LFUN_UP_SELECT:
        case LFUN_UP:
-               cell(cur.idx())->dispatch(cur, cmd);
+               if (!(cur.selection() && cur.selIsMultiCell()))
+                       cell(cur.idx())->dispatch(cur, cmd);
                cur.dispatched(); // override the cell's decision
-               if (sl == cur.top())
+               if (sl == cur.top()) {
                        // if our Text didn't do anything to the cursor
                        // then we try to put the cursor into the cell above
                        // setting also the right targetX.
+                       cur.selHandle(cmd.action == LFUN_UP_SELECT);
                        if (tabular.cellRow(cur.idx()) != 0) {
                                cur.idx() = tabular.cellAbove(cur.idx());
                                cur.pit() = cur.lastpit();
@@ -3305,10 +3535,16 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                                        tm.parMetrics(cur.lastpit());
                                cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
                        }
+               }
                if (sl == cur.top()) {
                        cmd = FuncRequest(LFUN_UP);
                        cur.undispatched();
                }
+               if (cur.selIsMultiCell()) {
+                       cur.pit() = 0;
+                       cur.pos() = cur.lastpos();
+                       return;
+               }
                break;
 
 //     case LFUN_SCREEN_DOWN: {
@@ -3380,7 +3616,7 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
        }
 
        case LFUN_CUT:
-               if (tablemode(cur)) {
+               if (cur.selIsMultiCell()) {
                        if (copySelection(cur)) {
                                cur.recordUndoInset(DELETE_UNDO);
                                cutSelection(cur);
@@ -3390,9 +3626,17 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                        cell(cur.idx())->dispatch(cur, cmd);
                break;
 
+       case LFUN_SELF_INSERT:
+               if (cur.selIsMultiCell()) {
+                       cur.recordUndoInset(DELETE_UNDO);
+                       cutSelection(cur);
+               }
+               cell(cur.idx())->dispatch(cur, cmd);
+               break;
+
        case LFUN_CHAR_DELETE_BACKWARD:
        case LFUN_CHAR_DELETE_FORWARD:
-               if (tablemode(cur)) {
+               if (cur.selIsMultiCell()) {
                        cur.recordUndoInset(DELETE_UNDO);
                        cutSelection(cur);
                }
@@ -3403,7 +3647,7 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
        case LFUN_COPY:
                if (!cur.selection())
                        break;
-               if (tablemode(cur)) {
+               if (cur.selIsMultiCell()) {
                        cur.finishUndo();
                        copySelection(cur);
                } else
@@ -3436,25 +3680,28 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
        }
 
        case LFUN_PASTE:
-               if (tabularStackDirty() && theClipboard().isInternal() ||
-                   !theClipboard().hasInternal() && theClipboard().hasLyXContents()) {
+               if (!tabularStackDirty()) {
+                       cell(cur.idx())->dispatch(cur, cmd);
+                       break;
+               }
+               if (theClipboard().isInternal() ||
+                   (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
                        cur.recordUndoInset(INSERT_UNDO);
                        pasteClipboard(cur);
-                       break;
                }
-               cell(cur.idx())->dispatch(cur, cmd);
                break;
 
        case LFUN_FONT_EMPH:
        case LFUN_FONT_BOLD:
+       case LFUN_FONT_BOLDSYMBOL:
        case LFUN_FONT_ROMAN:
        case LFUN_FONT_NOUN:
        case LFUN_FONT_ITAL:
        case LFUN_FONT_FRAK:
        case LFUN_FONT_TYPEWRITER:
        case LFUN_FONT_SANS:
-       case LFUN_FONT_FREE_APPLY:
-       case LFUN_FONT_FREE_UPDATE:
+       case LFUN_TEXTSTYLE_APPLY:
+       case LFUN_TEXTSTYLE_UPDATE:
        case LFUN_FONT_SIZE:
        case LFUN_FONT_UNDERLINE:
        case LFUN_LANGUAGE:
@@ -3462,7 +3709,7 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
        case LFUN_WORD_UPCASE:
        case LFUN_WORD_LOWCASE:
        case LFUN_CHARS_TRANSPOSE:
-               if (tablemode(cur)) {
+               if (cur.selIsMultiCell()) {
                        row_type rs, re;
                        col_type cs, ce;
                        getSelection(cur, rs, re, cs, ce);
@@ -3540,32 +3787,40 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                case Tabular::DELETE_COLUMN:
                case Tabular::COPY_ROW:
                case Tabular::COPY_COLUMN:
-               case Tabular::SET_ALL_LINES:
-               case Tabular::UNSET_ALL_LINES:
                case Tabular::SET_TOP_SPACE:
                case Tabular::SET_BOTTOM_SPACE:
                case Tabular::SET_INTERLINE_SPACE:
-               case Tabular::SET_BORDER_LINES:
                        status.clear();
                        return true;
 
                case Tabular::MULTICOLUMN:
+                       status.setEnabled(sel_row_start == sel_row_end);
                        status.setOnOff(tabular.isMultiColumn(cur.idx()));
                        break;
 
+               case Tabular::SET_ALL_LINES:
+               case Tabular::UNSET_ALL_LINES:
+               case Tabular::SET_BORDER_LINES:
+                       status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
+                       break;
+
                case Tabular::TOGGLE_LINE_TOP:
+                       status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
                        status.setOnOff(tabular.topLine(cur.idx()));
                        break;
 
                case Tabular::TOGGLE_LINE_BOTTOM:
+                       status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
                        status.setOnOff(tabular.bottomLine(cur.idx()));
                        break;
 
                case Tabular::TOGGLE_LINE_LEFT:
+                       status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
                        status.setOnOff(tabular.leftLine(cur.idx()));
                        break;
 
                case Tabular::TOGGLE_LINE_RIGHT:
+                       status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
                        status.setOnOff(tabular.rightLine(cur.idx()));
                        break;
 
@@ -3588,7 +3843,7 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                        break;
 
                case Tabular::ALIGN_BLOCK:
-                       status.enabled(!tabular.getPWidth(cur.idx()).zero());
+                       status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
                        status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
                        break;
 
@@ -3614,20 +3869,33 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                        break;
 
                case Tabular::SET_LONGTABULAR:
-                       status.setOnOff(tabular.isLongTabular());
+                       status.setOnOff(tabular.is_long_tabular);
                        break;
 
                case Tabular::UNSET_LONGTABULAR:
-                       status.setOnOff(!tabular.isLongTabular());
+                       status.setOnOff(!tabular.is_long_tabular);
                        break;
 
                case Tabular::TOGGLE_ROTATE_TABULAR:
                case Tabular::SET_ROTATE_TABULAR:
-                       status.setOnOff(tabular.getRotateTabular());
+                       status.setOnOff(tabular.rotate);
+                       break;
+
+               case Tabular::TABULAR_VALIGN_TOP:
+                       status.setOnOff(tabular.tabular_valignment 
+                               == Tabular::LYX_VALIGN_TOP);
+                       break;
+               case Tabular::TABULAR_VALIGN_MIDDLE:
+                       status.setOnOff(tabular.tabular_valignment 
+                               == Tabular::LYX_VALIGN_MIDDLE);
+                       break;
+               case Tabular::TABULAR_VALIGN_BOTTOM:
+                       status.setOnOff(tabular.tabular_valignment 
+                               == Tabular::LYX_VALIGN_BOTTOM);
                        break;
 
                case Tabular::UNSET_ROTATE_TABULAR:
-                       status.setOnOff(!tabular.getRotateTabular());
+                       status.setOnOff(!tabular.rotate);
                        break;
 
                case Tabular::TOGGLE_ROTATE_CELL:
@@ -3645,15 +3913,27 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                        status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
                        break;
 
-               case Tabular::SET_LTFIRSTHEAD:
-                       status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
+               // every row can only be one thing:
+               // either a footer or header or caption
+               case Tabular::SET_LTFIRSTHEAD:                  
+                       status.setEnabled(sel_row_start == sel_row_end
+                               && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
+                               && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
+                               && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
+                               && !tabular.ltCaption(sel_row_start));
+                       status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
                        break;
 
                case Tabular::UNSET_LTFIRSTHEAD:
-                       status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
+                       status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
                        break;
 
                case Tabular::SET_LTHEAD:
+                       status.setEnabled(sel_row_start == sel_row_end
+                               && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
+                               && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
+                               && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
+                               && !tabular.ltCaption(sel_row_start));
                        status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
                        break;
 
@@ -3662,6 +3942,11 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                        break;
 
                case Tabular::SET_LTFOOT:
+                       status.setEnabled(sel_row_start == sel_row_end
+                               && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
+                               && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
+                               && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
+                               && !tabular.ltCaption(sel_row_start));
                        status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
                        break;
 
@@ -3670,28 +3955,42 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                        break;
 
                case Tabular::SET_LTLASTFOOT:
-                       status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
+                       status.setEnabled(sel_row_start == sel_row_end
+                               && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
+                               && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
+                               && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
+                               && !tabular.ltCaption(sel_row_start));
+                       status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
                        break;
 
                case Tabular::UNSET_LTLASTFOOT:
-                       status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
+                       status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
                        break;
 
                case Tabular::SET_LTNEWPAGE:
                        status.setOnOff(tabular.getLTNewPage(sel_row_start));
                        break;
 
+               case Tabular::TOGGLE_LTCAPTION:
+                       status.setEnabled(sel_row_start == sel_row_end
+                               && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
+                               && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
+                               && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
+                               && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
+                       status.setOnOff(tabular.ltCaption(sel_row_start));
+                       break;
+
                case Tabular::SET_BOOKTABS:
-                       status.setOnOff(tabular.useBookTabs());
+                       status.setOnOff(tabular.use_booktabs);
                        break;
 
                case Tabular::UNSET_BOOKTABS:
-                       status.setOnOff(!tabular.useBookTabs());
+                       status.setOnOff(!tabular.use_booktabs);
                        break;
 
                default:
                        status.clear();
-                       status.enabled(false);
+                       status.setEnabled(false);
                        break;
                }
                return true;
@@ -3700,7 +3999,7 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
        // These are only enabled inside tabular
        case LFUN_CELL_BACKWARD:
        case LFUN_CELL_FORWARD:
-               status.enabled(true);
+               status.setEnabled(true);
                return true;
 
        // disable these with multiple cells selected
@@ -3719,10 +4018,11 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
        case LFUN_OPTIONAL_INSERT:
        case LFUN_BOX_INSERT:
        case LFUN_BRANCH_INSERT:
+       case LFUN_PHANTOM_INSERT:
        case LFUN_WRAP_INSERT:
        case LFUN_ERT_INSERT: {
-               if (tablemode(cur)) {
-                       status.enabled(false);
+               if (cur.selIsMultiCell()) {
+                       status.setEnabled(false);
                        return true;
                } else
                        return cell(cur.idx())->getStatus(cur, cmd, status);
@@ -3730,25 +4030,33 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
 
        // disable in non-fixed-width cells
        case LFUN_NEWLINE_INSERT:
-       case LFUN_BREAK_PARAGRAPH:
-       case LFUN_BREAK_PARAGRAPH_SKIP: {
+       case LFUN_BREAK_PARAGRAPH: {
                if (tabular.getPWidth(cur.idx()).zero()) {
-                       status.enabled(false);
+                       status.setEnabled(false);
                        return true;
                } else
                        return cell(cur.idx())->getStatus(cur, cmd, status);
        }
 
+       case LFUN_NEWPAGE_INSERT:
+               status.setEnabled(false);
+               return true;
+
        case LFUN_PASTE:
+               if (cur.selIsMultiCell()) {
+                       status.setEnabled(false);
+                       status.message(_("You cannot paste into a multicell selection."));
+                       return true;
+               }
                if (tabularStackDirty() && theClipboard().isInternal()) {
-                       status.enabled(true);
+                       status.setEnabled(true);
                        return true;
-               } else
-                       return cell(cur.idx())->getStatus(cur, cmd, status);
+               } 
+               return cell(cur.idx())->getStatus(cur, cmd, status);
 
        case LFUN_INSET_MODIFY:
                if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
-                       status.enabled(true);
+                       status.setEnabled(true);
                        return true;
                }
                // Fall through
@@ -3885,18 +4193,18 @@ int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
 {
        //lyxerr << "InsetTabular::editXY: " << this << endl;
-       cur.selection() = false;
+       cur.setSelection(false);
        cur.push(*this);
        cur.idx() = getNearestCell(cur.bv(), x, y);
        resetPos(cur);
-       return cur.bv().textMetrics(&cell(cur.idx())->text_).editXY(cur, x, y);
+       return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
 }
 
 
 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
 {
        cur.idx() = getNearestCell(cur.bv(), x, y);
-       cur.bv().textMetrics(&cell(cur.idx())->text_).setCursorFromCoordinates(cur, x, y);
+       cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
 }
 
 
@@ -3936,14 +4244,16 @@ void InsetTabular::resetPos(Cursor & cur) const
        BufferView & bv = cur.bv();
        int const maxwidth = bv.workWidth();
 
-       if (&cur.inset() != this) {
+       int const scx_old = scx_;
+       int const i = cur.find(this);
+       if (i == -1) {
                scx_ = 0;
        } else {
                int const X1 = 0;
                int const X2 = maxwidth;
                int const offset = ADD_TO_TABULAR_WIDTH + 2;
-               int const x1 = xo(cur.bv()) + cellXPos(cur.idx()) + offset;
-               int const x2 = x1 + tabular.columnWidth(cur.idx());
+               int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
+               int const x2 = x1 + tabular.columnWidth(cur[i].idx());
 
                if (x1 < X1)
                        scx_ = X1 + 20 - x1;
@@ -3953,16 +4263,18 @@ void InsetTabular::resetPos(Cursor & cur) const
                        scx_ = 0;
        }
 
-       cur.updateFlags(Update::Force | Update::FitCursor);
+       // only update if offset changed
+       if (scx_ != scx_old)
+               cur.updateFlags(Update::Force | Update::FitCursor);
 }
 
 
-void InsetTabular::moveNextCell(Cursor & cur)
+void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
 {
        if (isRightToLeft(cur)) {
                if (tabular.isFirstCellInRow(cur.idx())) {
                        row_type const row = tabular.cellRow(cur.idx());
-                       if (row == tabular.rowCount() - 1)
+                       if (row == tabular.row_info.size() - 1)
                                return;
                        cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
                } else {
@@ -3975,13 +4287,40 @@ void InsetTabular::moveNextCell(Cursor & cur)
                        return;
                ++cur.idx();
        }
+
+       cur.boundary(false);
+
+       if (cur.selIsMultiCell()) {
+               cur.pit() = cur.lastpit();
+               cur.pos() = cur.lastpos();
+               resetPos(cur);
+               return;
+       }
+
        cur.pit() = 0;
        cur.pos() = 0;
+
+       // in visual mode, place cursor at extreme left or right
+       
+       switch(entry_from) {
+
+       case ENTRY_DIRECTION_RIGHT:
+               cur.posVisToRowExtremity(false /* !left */);
+               break;
+       case ENTRY_DIRECTION_LEFT:
+               cur.posVisToRowExtremity(true /* left */);
+               break;
+       case ENTRY_DIRECTION_IGNORE:
+               // nothing to do in this case
+               break;
+
+       }
+
        resetPos(cur);
 }
 
 
-void InsetTabular::movePrevCell(Cursor & cur)
+void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
 {
        if (isRightToLeft(cur)) {
                if (tabular.isLastCellInRow(cur.idx())) {
@@ -4000,11 +4339,34 @@ void InsetTabular::movePrevCell(Cursor & cur)
                        return;
                --cur.idx();
        }
+
+       if (cur.selIsMultiCell()) {
+               cur.pit() = cur.lastpit();
+               cur.pos() = cur.lastpos();
+               resetPos(cur);
+               return;
+       }
+
        cur.pit() = cur.lastpit();
        cur.pos() = cur.lastpos();
 
-       // FIXME: this accesses the position cache before it is initialized
-       //resetPos(cur);
+       // in visual mode, place cursor at extreme left or right
+       
+       switch(entry_from) {
+
+       case ENTRY_DIRECTION_RIGHT:
+               cur.posVisToRowExtremity(false /* !left */);
+               break;
+       case ENTRY_DIRECTION_LEFT:
+               cur.posVisToRowExtremity(true /* left */);
+               break;
+       case ENTRY_DIRECTION_IGNORE:
+               // nothing to do in this case
+               break;
+
+       }
+
+       resetPos(cur);
 }
 
 
@@ -4159,23 +4521,23 @@ void InsetTabular::tabularFeatures(Cursor & cur,
        case Tabular::DELETE_ROW:
                for (row_type i = sel_row_start; i <= sel_row_end; ++i)
                        tabular.deleteRow(sel_row_start);
-               if (sel_row_start >= tabular.rowCount())
+               if (sel_row_start >= tabular.row_info.size())
                        --sel_row_start;
                cur.idx() = tabular.cellIndex(sel_row_start, column);
                cur.pit() = 0;
                cur.pos() = 0;
-               cur.selection() = false;
+               cur.setSelection(false);
                break;
 
        case Tabular::DELETE_COLUMN:
                for (col_type i = sel_col_start; i <= sel_col_end; ++i)
                        tabular.deleteColumn(sel_col_start);
-               if (sel_col_start >= tabular.columnCount())
+               if (sel_col_start >= tabular.column_info.size())
                        --sel_col_start;
                cur.idx() = tabular.cellIndex(row, sel_col_start);
                cur.pit() = 0;
                cur.pos() = 0;
-               cur.selection() = false;
+               cur.setSelection(false);
                break;
 
        case Tabular::COPY_ROW:
@@ -4245,13 +4607,6 @@ void InsetTabular::tabularFeatures(Cursor & cur,
                break;
 
        case Tabular::MULTICOLUMN: {
-               if (sel_row_start != sel_row_end) {
-                       // FIXME: Need I say it ? This is horrible.
-                       // FIXME UNICODE
-                       Alert::error(_("Error setting multicolumn"),
-                                    _("You cannot set multicolumn vertically."));
-                       return;
-               }
                if (!cur.selection()) {
                        // just multicol for one single cell
                        // check whether we are completely in a multicol
@@ -4269,7 +4624,7 @@ void InsetTabular::tabularFeatures(Cursor & cur,
                cur.idx() = s_start;
                cur.pit() = 0;
                cur.pos() = 0;
-               cur.selection() = false;
+               cur.setSelection(false);
                break;
        }
 
@@ -4294,23 +4649,35 @@ void InsetTabular::tabularFeatures(Cursor & cur,
                break;
 
        case Tabular::SET_LONGTABULAR:
-               tabular.setLongTabular(true);
+               tabular.is_long_tabular = true;
                break;
 
        case Tabular::UNSET_LONGTABULAR:
-               tabular.setLongTabular(false);
+               tabular.is_long_tabular = false;
                break;
 
        case Tabular::SET_ROTATE_TABULAR:
-               tabular.setRotateTabular(true);
+               tabular.rotate = true;
                break;
 
        case Tabular::UNSET_ROTATE_TABULAR:
-               tabular.setRotateTabular(false);
+               tabular.rotate = false;
                break;
 
        case Tabular::TOGGLE_ROTATE_TABULAR:
-               tabular.setRotateTabular(!tabular.getRotateTabular());
+               tabular.rotate = !tabular.rotate;
+               break;
+
+       case Tabular::TABULAR_VALIGN_TOP:
+               tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
+               break;
+
+       case Tabular::TABULAR_VALIGN_MIDDLE:
+               tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
+               break;
+
+       case Tabular::TABULAR_VALIGN_BOTTOM:
+               tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
                break;
 
        case Tabular::SET_ROTATE_CELL:
@@ -4384,12 +4751,19 @@ void InsetTabular::tabularFeatures(Cursor & cur,
                tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
                break;
 
+       case Tabular::TOGGLE_LTCAPTION:
+               cur.idx() = tabular.setLTCaption(row, !tabular.ltCaption(row));
+               cur.pit() = 0;
+               cur.pos() = 0;
+               cur.setSelection(false);
+               break;
+
        case Tabular::SET_BOOKTABS:
-               tabular.setBookTabs(true);
+               tabular.use_booktabs = true;
                break;
 
        case Tabular::UNSET_BOOKTABS:
-               tabular.setBookTabs(false);
+               tabular.use_booktabs = false;
                break;
 
        case Tabular::SET_TOP_SPACE: {
@@ -4483,24 +4857,17 @@ bool InsetTabular::copySelection(Cursor & cur)
                paste_tabular->deleteRow(0);
 
        row_type const rows = re - rs + 1;
-       while (paste_tabular->rowCount() > rows)
+       while (paste_tabular->row_info.size() > rows)
                paste_tabular->deleteRow(rows);
 
        for (col_type i = 0; i < cs; ++i)
                paste_tabular->deleteColumn(0);
 
        col_type const columns = ce - cs + 1;
-       while (paste_tabular->columnCount() > columns)
+       while (paste_tabular->column_info.size() > columns)
                paste_tabular->deleteColumn(columns);
 
-       // We clear all the InsetTableCell pointers, since they
-       // might now become invalid and there is no point in having
-       // them point to temporary things in paste_tabular.
-       for (row_type i = 0; i < paste_tabular->rowCount(); ++i)
-               for (col_type j = 0; j < paste_tabular->columnCount(); ++j) {
-                       paste_tabular->cellInset(i,j)->setCellData(0);
-                       paste_tabular->cellInset(i,j)->setTabular(0);
-               }
+       paste_tabular->setBuffer(tabular.buffer());
 
        odocstringstream os;
        OutputParams const runparams(0);
@@ -4525,10 +4892,10 @@ bool InsetTabular::pasteClipboard(Cursor & cur)
        col_type const actcol = tabular.cellColumn(cur.idx());
        row_type const actrow = tabular.cellRow(cur.idx());
        for (row_type r1 = 0, r2 = actrow;
-            r1 < paste_tabular->rowCount() && r2 < tabular.rowCount();
+            r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
             ++r1, ++r2) {
                for (col_type c1 = 0, c2 = actcol;
-                   c1 < paste_tabular->columnCount() && c2 < tabular.columnCount();
+                   c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
                    ++c1, ++c2) {
                        if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
                            tabular.isPartOfMultiColumn(r2, c2))
@@ -4543,11 +4910,9 @@ bool InsetTabular::pasteClipboard(Cursor & cur)
                        }
                        shared_ptr<InsetTableCell> inset(
                                new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
-                       // note that setCellInset will call InsetTableCell::setCellData()
-                       // and InsetTableCell::setTabular()
                        tabular.setCellInset(r2, c2, inset);
                        // FIXME: change tracking (MG)
-                       inset->setChange(Change(cur.buffer().params().trackChanges ?
+                       inset->setChange(Change(buffer().params().trackChanges ?
                                                Change::INSERTED : Change::UNCHANGED));
                        cur.pos() = 0;
                }
@@ -4568,7 +4933,7 @@ void InsetTabular::cutSelection(Cursor & cur)
                for (col_type j = cs; j <= ce; ++j) {
                        shared_ptr<InsetTableCell> t
                                = cell(tabular.cellIndex(i, j));
-                       if (cur.buffer().params().trackChanges)
+                       if (buffer().params().trackChanges)
                                // FIXME: Change tracking (MG)
                                t->setChange(Change(Change::DELETED));
                        else
@@ -4587,13 +4952,34 @@ void InsetTabular::cutSelection(Cursor & cur)
 
 bool InsetTabular::isRightToLeft(Cursor & cur) const
 {
-       BOOST_ASSERT(cur.depth() > 1);
+       LASSERT(cur.depth() > 1, /**/);
        Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
        pos_type const parentpos = cur[cur.depth() - 2].pos();
-       return parentpar.getFontSettings(cur.bv().buffer().params(),
+       return parentpar.getFontSettings(buffer().params(),
                                         parentpos).language()->rightToLeft();
 }
 
+docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
+                                 bool intoInsets)
+{
+       LASSERT(stidx <= enidx, return docstring());
+       docstring retval;
+       col_type const col1 = tabular.cellColumn(stidx);
+       col_type const col2 = tabular.cellColumn(enidx);
+       row_type const row1 = tabular.cellRow(stidx);
+       row_type const row2 = tabular.cellRow(enidx);
+       bool first = true;
+       for (col_type col = col1; col <= col2; col++)
+               for (row_type row = row1; row <= row2; row++) {
+                       if (!first)
+                               retval += "\n";
+                       else
+                               first = false;
+                       retval += tabular.cellInset(row, col)->asString(intoInsets);
+               }
+       return retval;
+}
+
 
 void InsetTabular::getSelection(Cursor & cur,
        row_type & rs, row_type & re, col_type & cs, col_type & ce) const
@@ -4649,7 +5035,7 @@ bool InsetTabular::allowParagraphCustomization(idx_type cell) const
 }
 
 
-bool InsetTabular::forceEmptyLayout(idx_type cell) const
+bool InsetTabular::forcePlainLayout(idx_type cell) const
 {
        return !tabular.getPWidth(cell).zero();
 }
@@ -4700,11 +5086,11 @@ bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
        }
 
        size_t op = 0;
-       idx_type const cells = loctab->cellCount();
+       idx_type const cells = loctab->numberofcells;
        p = 0;
        cols = ocol;
-       rows = loctab->rowCount();
-       col_type const columns = loctab->columnCount();
+       rows = loctab->row_info.size();
+       col_type const columns = loctab->column_info.size();
 
        while (cell < cells && p < len && row < rows &&
               (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
@@ -4716,7 +5102,7 @@ bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
                        // we can only set this if we are not too far right
                        if (cols < columns) {
                                shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
-                               Font const font = bv.textMetrics(&inset->text_).
+                               Font const font = bv.textMetrics(&inset->text()).
                                        displayFont(0, 0);
                                inset->setText(buf.substr(op, p - op), font,
                                               buffer().params().trackChanges);
@@ -4728,7 +5114,7 @@ bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
                        // we can only set this if we are not too far right
                        if (cols < columns) {
                                shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
-                               Font const font = bv.textMetrics(&inset->text_).
+                               Font const font = bv.textMetrics(&inset->text()).
                                        displayFont(0, 0);
                                inset->setText(buf.substr(op, p - op), font,
                                               buffer().params().trackChanges);
@@ -4745,7 +5131,7 @@ bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
        // check for the last cell if there is no trailing '\n'
        if (cell < cells && op < len) {
                shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
-               Font const font = bv.textMetrics(&inset->text_).displayFont(0, 0);
+               Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
                inset->setText(buf.substr(op, len - op), font,
                        buffer().params().trackChanges);
        }
@@ -4755,8 +5141,8 @@ bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
 
 void InsetTabular::addPreview(PreviewLoader & loader) const
 {
-       row_type const rows = tabular.rowCount();
-       col_type const columns = tabular.columnCount();
+       row_type const rows = tabular.row_info.size();
+       col_type const columns = tabular.column_info.size();
        for (row_type i = 0; i < rows; ++i) {
                for (col_type j = 0; j < columns; ++j)
                        tabular.cellInset(i, j)->addPreview(loader);
@@ -4764,12 +5150,6 @@ void InsetTabular::addPreview(PreviewLoader & loader) const
 }
 
 
-bool InsetTabular::tablemode(Cursor & cur) const
-{
-       return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
-}
-
-
 bool InsetTabular::completionSupported(Cursor const & cur) const
 {
        Cursor const & bvCur = cur.bv().cursor();