]> git.lyx.org Git - lyx.git/blobdiff - src/insets/InsetTabular.cpp
delete unused variable, fix multicolumn and some clean up
[lyx.git] / src / insets / InsetTabular.cpp
index ca41cd91efde10c856db137085dd6af01d009b71..8f2c5c38da4e3663ce42fb03262a49f39c89461b 100644 (file)
@@ -3,14 +3,16 @@
  * 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
+ * \author Uwe Stöhr
+ * \author Edwin Leuven
  *
  * Full author contact details are available in file CREDITS.
  */
 #include "Language.h"
 #include "LaTeXFeatures.h"
 #include "Lexer.h"
-#include "LyXFunc.h"
+#include "LyX.h"
 #include "LyXRC.h"
 #include "MetricsInfo.h"
 #include "OutputParams.h"
-#include "paragraph_funcs.h"
+#include "output_xhtml.h"
 #include "Paragraph.h"
 #include "ParagraphParameters.h"
 #include "ParIterator.h"
@@ -69,7 +71,6 @@ using namespace std;
 using namespace lyx::support;
 
 using boost::shared_ptr;
-using boost::dynamic_pointer_cast;
 
 
 namespace lyx {
@@ -129,6 +130,7 @@ TabularFeature tabularFeature[] =
        { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
        { Tabular::M_VALIGN_MIDDLE, "m-valign-middle" },
        { Tabular::MULTICOLUMN, "multicolumn" },
+       { Tabular::MULTIROW, "multirow" },
        { Tabular::SET_ALL_LINES, "set-all-lines" },
        { Tabular::UNSET_ALL_LINES, "unset-all-lines" },
        { Tabular::SET_LONGTABULAR, "set-longtabular" },
@@ -153,13 +155,20 @@ TabularFeature tabularFeature[] =
        { 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_SPECIAL_MULTICOLUMN, "set-special-multicolumn" },
+       { Tabular::SET_SPECIAL_MULTIROW, "set-special-multirow" },
        { Tabular::SET_BOOKTABS, "set-booktabs" },
        { Tabular::UNSET_BOOKTABS, "unset-booktabs" },
        { Tabular::SET_TOP_SPACE, "set-top-space" },
        { 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::LONGTABULAR_ALIGN_LEFT, "longtabular-align-left" },
+       { Tabular::LONGTABULAR_ALIGN_CENTER, "longtabular-align-center" },
+       { Tabular::LONGTABULAR_ALIGN_RIGHT, "longtabular-align-right" },        
        { Tabular::LAST_ACTION, "" }
 };
 
@@ -254,6 +263,20 @@ string const tostr(LyXAlignment const & num)
 }
 
 
+string const tostr(Tabular::HAlignment const & num)
+{
+       switch (num) {
+       case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
+               return "left";
+       case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
+               return "center";
+       case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
+               return "right";
+       }
+       return string();
+}
+
+
 string const tostr(Tabular::VAlignment const & num)
 {
        switch (num) {
@@ -301,6 +324,20 @@ bool string2type(string const str, LyXAlignment & num)
 }
 
 
+bool string2type(string const str, Tabular::HAlignment & num)
+{
+       if (str == "left")
+               num = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
+       else if (str == "center" )
+               num = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
+       else if (str == "right")
+               num = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
+       else
+               return false;
+       return true;
+}
+
+
 bool string2type(string const str, Tabular::VAlignment & num)
 {
        if (str == "top")
@@ -390,6 +427,14 @@ bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
 }
 
 
+bool getTokenValue(string const & str, char const * token,
+                                  Tabular::HAlignment & num)
+{
+       string tmp;
+       return getTokenValue(str, token, tmp) && string2type(tmp, num);
+}
+
+
 bool getTokenValue(string const & str, char const * token,
                                   Tabular::VAlignment & num)
 {
@@ -472,10 +517,11 @@ string const featureAsString(Tabular::Feature feature)
 /////////////////////////////////////////////////////////////////////
 
 
-Tabular::CellData::CellData(Buffer & buf)
+Tabular::CellData::CellData(Buffer * buf)
        : cellno(0),
          width(0),
          multicolumn(Tabular::CELL_NORMAL),
+         multirow(Tabular::CELL_NORMAL),
          alignment(LYX_ALIGN_CENTER),
          valignment(LYX_VALIGN_TOP),
          top_line(false),
@@ -486,8 +532,7 @@ Tabular::CellData::CellData(Buffer & buf)
          rotate(false),
          inset(new InsetTableCell(buf))
 {
-       inset->setBuffer(const_cast<Buffer &>(buf));
-       inset->paragraphs().back().setLayout(buf.params().documentClass().plainLayout());
+       inset->setBuffer(*buf);
 }
 
 
@@ -495,6 +540,7 @@ Tabular::CellData::CellData(CellData const & cs)
        : cellno(cs.cellno),
          width(cs.width),
          multicolumn(cs.multicolumn),
+         multirow(cs.multirow),
          alignment(cs.alignment),
          valignment(cs.valignment),
          top_line(cs.top_line),
@@ -520,6 +566,7 @@ void Tabular::CellData::swap(CellData & rhs)
        std::swap(cellno, rhs.cellno);
        std::swap(width, rhs.width);
        std::swap(multicolumn, rhs.multicolumn);
+       std::swap(multirow, rhs.multirow);
        std::swap(alignment, rhs.alignment);
        std::swap(valignment, rhs.valignment);
        std::swap(top_line, rhs.top_line);
@@ -564,7 +611,7 @@ Tabular::ltType::ltType()
 {}
 
 
-Tabular::Tabular(Buffer & buffer, row_type rows_arg, col_type columns_arg)
+Tabular::Tabular(Buffer * buffer, row_type rows_arg, col_type columns_arg)
 {
        init(buffer, rows_arg, columns_arg);
 }
@@ -573,20 +620,19 @@ Tabular::Tabular(Buffer & buffer, row_type rows_arg, col_type columns_arg)
 void Tabular::setBuffer(Buffer & buffer)
 {
        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)
+       row_type const nrows = row_info.size();
+       col_type const ncols = column_info.size();
+       for (row_type i = 0; i < nrows; ++i)
+               for (col_type j = 0; j < ncols; ++j)
                        cell_info[i][j].inset->setBuffer(*buffer_);
 }
 
 
 // activates all lines and sets all widths to 0
-void Tabular::init(Buffer & buf, row_type rows_arg,
+void Tabular::init(Buffer * buf, row_type rows_arg,
                      col_type columns_arg)
 {
-       buffer_ = &buf;
+       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)));
@@ -595,6 +641,8 @@ void Tabular::init(Buffer & buf, row_type rows_arg,
        cell_info.reserve(100);
        updateIndexes();
        is_long_tabular = false;
+       tabular_valignment = LYX_VALIGN_MIDDLE;
+       longtabular_alignment = LYX_LONGTABULAR_ALIGN_CENTER;
        rotate = false;
        use_booktabs = false;
        size_t row_count = row_info.size();
@@ -613,30 +661,25 @@ void Tabular::init(Buffer & buf, row_type rows_arg,
 
 void Tabular::appendRow(idx_type const cell)
 {
-       BufferParams const & bp = buffer().params();
        row_type const row = cellRow(cell);
 
-       row_vector::iterator rit = row_info.begin() + row;
-       row_info.insert(rit, RowData());
-       // now set the values of the row before
-       row_info[row] = row_info[row + 1];
+       row_info.insert(row_info.begin() + row + 1, RowData());
+       row_info[row + 1] = row_info[row];
 
-       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())));
-
-       for (row_type i = 0; i <= row; ++i)
-               swap(cell_info[i], old[i]);
-       for (row_type i = row + 2; i < nrows; ++i)
-               swap(cell_info[i], old[i - 1]);
-
+       cell_info.insert(cell_info.begin() + row + 1,
+               cell_vector(ncols, CellData(buffer_)));
+       for (col_type c = 0; c < ncols; ++c) {
+               if (cell_info[row][c].multirow == CELL_BEGIN_OF_MULTIROW)
+                       cell_info[row + 1][c].multirow = CELL_PART_OF_MULTIROW;
+               else
+                       cell_info[row + 1][c].multirow = cell_info[row][c].multirow;
+       }
        updateIndexes();
+
        for (col_type c = 0; c < ncols; ++c) {
+               if (isPartOfMultiRow(row, c))
+                       continue;
                // inherit line settings
                idx_type const i = cellIndex(row + 1, c);
                idx_type const j = cellIndex(row, c);
@@ -648,7 +691,7 @@ void Tabular::appendRow(idx_type const cell)
                        setBottomLine(j, false);
                }
                // mark track changes
-               if (bp.trackChanges)
+               if (buffer().params().trackChanges)
                        cellInfo(i).inset->setChange(Change(Change::INSERTED));
        }
 }
@@ -660,6 +703,15 @@ void Tabular::deleteRow(row_type const row)
        if (row_info.size() == 1)
                return;
 
+       size_t const column_count = column_info.size();
+       for (col_type i = 0; i < column_count; ++i) {
+               // Care about multirow cells
+               if (row + 1 < row_info.size() &&
+                   cell_info[row][i].multirow == CELL_BEGIN_OF_MULTIROW &&
+                   cell_info[row][i + 1].multirow == CELL_PART_OF_MULTIROW) {
+                               cell_info[row][i + 1].multirow = CELL_BEGIN_OF_MULTIROW;
+               }
+       }
        row_info.erase(row_info.begin() + row);
        cell_info.erase(cell_info.begin() + row);
        updateIndexes();
@@ -682,23 +734,18 @@ void Tabular::copyRow(row_type const row)
 void Tabular::appendColumn(idx_type const cell)
 {
        col_type const c = cellColumn(cell);
-       column_vector::iterator cit = column_info.begin() + c + 1;
-       column_info.insert(cit, ColumnData());
-       row_type const nrows = row_info.size();
-       // set the column values of the column before
+       
+       column_info.insert(column_info.begin() + c + 1, ColumnData());
        column_info[c + 1] = column_info[c];
 
+       row_type const nrows = row_info.size();
        for (row_type r = 0; r < nrows; ++r) {
                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.
+                       CellData(buffer_));
                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) {
@@ -712,61 +759,63 @@ void Tabular::appendColumn(idx_type const cell)
                        setRightLine(i, true);
                        setRightLine(j, false);
                }
-               //
-               cellInfo(i).inset->clear();
                if (buffer().params().trackChanges)
                        cellInfo(i).inset->setChange(Change(Change::INSERTED));
        }
 }
 
 
-void Tabular::deleteColumn(col_type const column)
+void Tabular::deleteColumn(col_type const col)
 {
        // Not allowed to delete last column
        if (column_info.size() == 1)
                return;
 
-       column_info.erase(column_info.begin() + column);
-       size_t row_count = row_info.size();
-       for (row_type i = 0; i < row_count; ++i) {
+       row_type const nrows = row_info.size();
+       for (row_type r = 0; r < nrows; ++r) {
                // Care about multicolumn cells
-               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;
+               if (col + 1 < column_info.size() &&
+                   cell_info[r][col].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
+                   cell_info[r][col + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
+                               cell_info[r][col + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
                }
-               cell_info[i].erase(cell_info[i].begin() + column);
+               cell_info[r].erase(cell_info[r].begin() + col);
        }
+       column_info.erase(column_info.begin() + col);
        updateIndexes();
 }
 
 
-void Tabular::copyColumn(col_type const column)
+void Tabular::copyColumn(col_type const col)
 {
        BufferParams const & bp = buffer().params();
-       column_info.insert(column_info.begin() + column, column_info[column]);
-
-       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]);
+       column_info.insert(column_info.begin() + col, column_info[col]);
 
-       if (bp.trackChanges)
-               for (row_type i = 0; i < row_count; ++i)
-                       cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
+       row_type nrows = row_info.size();
+       for (row_type r = 0; r < nrows; ++r) {
+               cell_info[r].insert(cell_info[r].begin() + col, cell_info[r][col]);
+               if (bp.trackChanges)
+                       cell_info[r][col + 1].inset->setChange(Change(Change::INSERTED));
+       }
        updateIndexes();
 }
 
 
 void Tabular::updateIndexes()
 {
+       setBuffer(buffer());
        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) {
-                       if (!isPartOfMultiColumn(row, column))
+                       if (!isPartOfMultiColumn(row, column)
+                               && !isPartOfMultiRow(row, column))
                                ++numberofcells;
-                       cell_info[row][column].cellno = numberofcells - 1;
+                       if (isPartOfMultiRow(row, column))
+                               cell_info[row][column].cellno = cell_info[row - 1][column].cellno;
+                       else
+                               cell_info[row][column].cellno = numberofcells - 1;
                }
 
        rowofcell.resize(numberofcells);
@@ -774,7 +823,8 @@ void Tabular::updateIndexes()
        idx_type i = 0;
        for (row_type row = 0; row < nrows; ++row)
                for (col_type column = 0; column < ncols; ++column) {
-                       if (isPartOfMultiColumn(row, column))
+                       if (isPartOfMultiColumn(row, column)
+                               || isPartOfMultiRow(row, column))
                                continue;
                        rowofcell[i] = row;
                        columnofcell[i] = column;
@@ -785,9 +835,8 @@ void Tabular::updateIndexes()
 }
 
 
-Tabular::idx_type Tabular::numberOfCellsInRow(idx_type const cell) const
+Tabular::idx_type Tabular::numberOfCellsInRow(row_type const row) const
 {
-       row_type const row = cellRow(cell);
        idx_type result = 0;
        for (col_type i = 0; i < column_info.size(); ++i)
                if (cell_info[row][i].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
@@ -826,11 +875,11 @@ bool Tabular::rightLine(idx_type cell) const
 
 bool Tabular::topAlreadyDrawn(idx_type cell) const
 {
-       row_type row = cellRow(cell);
+       row_type const row = cellRow(cell);
        if (row == 0)
                return false;
-       idx_type i = cellIndex(row - 1, cellColumn(cell));
-       return !rowTopLine(row) && bottomLine(i);
+       
+       return !rowTopLine(row) && bottomLine(cellAbove(cell));
 }
 
 
@@ -850,7 +899,7 @@ bool Tabular::isLastRow(idx_type cell) const
 }
 
 
-int Tabular::getAdditionalHeight(row_type row) const
+int Tabular::interRowSpace(row_type row) const
 {
        if (!row || row >= row_info.size())
                return 0;
@@ -864,11 +913,11 @@ int Tabular::getAdditionalHeight(row_type row) const
 }
 
 
-int Tabular::getAdditionalWidth(idx_type cell) const
+int Tabular::interColumnSpace(idx_type cell) const
 {
        col_type const nextcol = cellColumn(cell) + columnSpan(cell);
-       if (rightLine(cell) 
-               && nextcol < column_info.size() && leftLine(cellIndex(cellRow(cell), nextcol)))
+       if (rightLine(cell) && nextcol < column_info.size()
+               && leftLine(cellIndex(cellRow(cell), nextcol)))
                return WIDTH_OF_LINE;
        return 0;
 }
@@ -885,6 +934,24 @@ int Tabular::columnWidth(idx_type cell) const
 }
 
 
+int Tabular::rowHeight(idx_type cell) const
+{
+       row_type const span = rowSpan(cell);
+       row_type const row = cellRow(cell);
+       int h = rowAscent(row) + rowDescent(row);
+
+       for(row_type r = row; r < row + span ; ++r) {
+               if (r > row) {
+                       h += rowAscent(r);
+                       h += interRowSpace(r);
+               }
+               if (r < row + span - 1)
+                       h += rowDescent(r);
+       }
+       return h;
+}
+
+
 bool Tabular::updateColumnWidths()
 {
        col_type const ncols = column_info.size();
@@ -939,7 +1006,7 @@ int Tabular::width() const
 void Tabular::setCellWidth(idx_type cell, int new_width)
 {
        cellInfo(cell).width = new_width + 2 * WIDTH_OF_LINE 
-               + getAdditionalWidth(cell);
+               + interColumnSpace(cell);
 }
 
 
@@ -986,7 +1053,7 @@ void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
        // reset layout
        cur.push(*inset);
        // undo information has already been recorded
-       inset->getText(0)->setLayout(cur.bv().buffer(), 0, cur.lastpit() + 1,
+       inset->getText(0)->setLayout(0, cur.lastpit() + 1,
                        bp.documentClass().plainLayoutName());
        cur.pop();
 }
@@ -1018,12 +1085,10 @@ 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;
-       if ((!column_info[c].p_width.zero() && !multicol)
-           || (multicol && !cell_info[r][c].p_width.zero())) {
-               cell_info[r][c].inset->toggleFixedWidth(true);
-               return true;
-       }
-       return false;
+       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;
 }
 
 
@@ -1055,7 +1120,7 @@ bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
                                 Tabular::Feature what)
 {
-       if (what == SET_SPECIAL_MULTI)
+       if (what == SET_SPECIAL_MULTICOLUMN)
                cellInfo(cell).align_special = special;
        else
                column_info[cellColumn(cell)].align_special = special;
@@ -1096,22 +1161,24 @@ void Tabular::setRightLine(idx_type cell, bool line)
 
 bool Tabular::rowTopLine(row_type r) const
 {
-       idx_type i0 = getFirstCellInRow(r);
-       idx_type i1 = getLastCellInRow(r);
+       col_type const ncols = column_info.size();
        bool all_rows_set = true;
-       for (idx_type j = i0; all_rows_set && j <= i1; ++j)
-               all_rows_set = cellInfo(j).top_line;
+       for (col_type c = 0; all_rows_set && c < ncols; ++c) {
+               idx_type const i = cellIndex(r, c);
+               all_rows_set = cellInfo(i).top_line;
+       }
        return all_rows_set;
 }
 
 
 bool Tabular::rowBottomLine(row_type r) const
 {
-       idx_type i0 = getFirstCellInRow(r);
-       idx_type i1 = getLastCellInRow(r);
+       col_type const ncols = column_info.size();
        bool all_rows_set = true;
-       for (idx_type j = i0; all_rows_set && j <= i1; ++j)
-               all_rows_set = cellInfo(j).bottom_line;
+       for (col_type c = 0; all_rows_set && c < ncols; ++c) {
+               idx_type const i = cellIndex(r, c);
+               all_rows_set = cellInfo(i).bottom_line;
+       }
        return all_rows_set;
 }
 
@@ -1149,8 +1216,8 @@ bool Tabular::columnRightLine(col_type c) const
                idx_type i = cellIndex(r, c);
                if (c == cellColumn(i) + columnSpan(i) - 1) {
                        ++total;
-                       bool left = c + 1 < column_info.size() 
-                               && cellInfo(cellIndex(r, c + 1)).left_line
+                       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;
@@ -1191,9 +1258,10 @@ int Tabular::cellWidth(idx_type cell) const
 }
 
 
-int Tabular::getBeginningOfTextInCell(idx_type cell) const
+int Tabular::textHOffset(idx_type cell) const
 {
-       int x = 0;
+       // the LaTeX Way :-(
+       int x = WIDTH_OF_LINE;
 
        switch (getAlignment(cell)) {
        case LYX_ALIGN_CENTER:
@@ -1201,44 +1269,52 @@ int Tabular::getBeginningOfTextInCell(idx_type cell) const
                break;
        case LYX_ALIGN_RIGHT:
                x += columnWidth(cell) - cellWidth(cell);
-               // + getAdditionalWidth(cell);
+               // + interColumnSpace(cell);
                break;
        default:
                // LYX_ALIGN_LEFT: nothing :-)
                break;
        }
 
-       // the LaTeX Way :-(
-       x += WIDTH_OF_LINE;
        return x;
 }
 
 
-bool Tabular::isFirstCellInRow(idx_type cell) const
+int Tabular::textVOffset(idx_type cell) const
 {
-       return cellColumn(cell) == 0;
+       int h = rowHeight(cell);
+       
+       int y = 0;
+       switch (getVAlignment(cell)) {
+          case LYX_VALIGN_TOP:
+                  break;
+          case LYX_VALIGN_MIDDLE:
+                  y += h/2;
+                  break;
+          case LYX_VALIGN_BOTTOM:
+                  y += h;
+                  break;
+       }
+       
+       return y;
 }
 
 
 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
 {
-       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) == column_info.size() - 1;
+       col_type c = 0;
+       while (cell_info[row][c].multirow == CELL_PART_OF_MULTIROW)
+               ++c;
+       return cell_info[row][c].cellno;
 }
 
 
 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
 {
-       if (row > row_info.size() - 1)
-               row = row_info.size() - 1;
-       return cell_info[row][column_info.size() - 1].cellno;
+       col_type c = column_info.size() - 1;
+       while (cell_info[row][c].multirow == CELL_PART_OF_MULTIROW)
+               --c;
+       return cell_info[row][c].cellno;
 }
 
 
@@ -1295,8 +1371,14 @@ void Tabular::write(ostream & os) const
           << write_attribute("footBottomDL", endfoot.bottomDL)
           << write_attribute("lastFootTopDL", endlastfoot.topDL)
           << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
-          << write_attribute("lastFootEmpty", endlastfoot.empty)
-          << ">\n";
+          << write_attribute("lastFootEmpty", endlastfoot.empty);
+       // longtables cannot be aligned vertically
+       if (!is_long_tabular)
+          os << write_attribute("tabularvalignment", tabular_valignment);
+       if (is_long_tabular)
+          os << write_attribute("longtabularalignment",
+                                longtabular_alignment);
+       os << ">\n";
        for (col_type j = 0; j < column_info.size(); ++j) {
                os << "<column"
                   << write_attribute("alignment", column_info[j].alignment)
@@ -1330,6 +1412,7 @@ void Tabular::write(ostream & os) const
                for (col_type j = 0; j < column_info.size(); ++j) {
                        os << "<cell"
                           << write_attribute("multicolumn", cell_info[i][j].multicolumn)
+                          << write_attribute("multirow", cell_info[i][j].multirow)
                           << write_attribute("alignment", cell_info[i][j].alignment)
                           << write_attribute("valignment", cell_info[i][j].valignment)
                           << write_attribute("topline", cell_info[i][j].top_line)
@@ -1374,7 +1457,7 @@ void Tabular::read(Lexer & lex)
        int columns_arg;
        if (!getTokenValue(line, "columns", columns_arg))
                return;
-       init(buffer(), rows_arg, columns_arg);
+       init(buffer_, rows_arg, columns_arg);
        l_getline(is, line);
        if (!prefixIs(line, "<features")) {
                lyxerr << "Wrong tabular format (expected <features ...> got"
@@ -1384,6 +1467,8 @@ 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, "longtabularalignment", longtabular_alignment);
        getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
        getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
        getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
@@ -1435,6 +1520,7 @@ void Tabular::read(Lexer & lex)
                                return;
                        }
                        getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
+                       getTokenValue(line, "multirow", cell_info[i][j].multirow);
                        getTokenValue(line, "alignment", cell_info[i][j].alignment);
                        getTokenValue(line, "valignment", cell_info[i][j].valignment);
                        getTokenValue(line, "topline", cell_info[i][j].top_line);
@@ -1474,14 +1560,19 @@ void Tabular::read(Lexer & lex)
 
 bool Tabular::isMultiColumn(idx_type cell) const
 {
-       return cellInfo(cell).multicolumn != CELL_NORMAL;
+       if (cellInfo(cell).multicolumn == CELL_BEGIN_OF_MULTICOLUMN
+               || cellInfo(cell).multicolumn == CELL_PART_OF_MULTICOLUMN)
+               return true;
+       else
+               return false;
 }
 
 
 bool Tabular::isMultiColumnReal(idx_type cell) const
 {
        return cellColumn(cell) != cellRightColumn(cell) &&
-                       cellInfo(cell).multicolumn != CELL_NORMAL;
+               (cellInfo(cell).multicolumn == CELL_BEGIN_OF_MULTICOLUMN
+                || cellInfo(cell).multicolumn == CELL_PART_OF_MULTICOLUMN);
 }
 
 
@@ -1507,40 +1598,79 @@ void Tabular::setMultiColumn(idx_type cell, idx_type number)
 }
 
 
+bool Tabular::isMultiRow(idx_type cell) const
+{
+       return (cellInfo(cell).multirow == CELL_BEGIN_OF_MULTIROW
+               || cellInfo(cell).multirow == CELL_PART_OF_MULTIROW);
+}
+
+
+void Tabular::setMultiRow(idx_type cell, idx_type number)
+{
+       idx_type const column = cellColumn(cell);
+       idx_type row = cellRow(cell);
+       idx_type const ncolumns = column_info.size();
+       CellData & cs = cellInfo(cell);
+       cs.multirow = CELL_BEGIN_OF_MULTIROW;
+       // FIXME: the horizontal alignment can only be changed for
+       // the whole table, support for this needs to be implemented
+       // assigning this to uwestoehr
+       cs.valignment = LYX_VALIGN_MIDDLE;
+       // set the bottom row of the last selected cell
+       setBottomLine(cell, bottomLine(cell + (number - 1)*ncolumns));
+       for (idx_type i = 1; i < number; ++i) {
+               CellData & cs1 = cell_info[row + i][column];
+               cs1.multirow = CELL_PART_OF_MULTIROW;
+               cs.inset->appendParagraphs(cs1.inset->paragraphs());
+               cs1.inset->clear();
+       }
+       updateIndexes();
+}
+
+
 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
 {
        row_type const row = cellRow(cell);
        col_type const ncols = column_info.size();
-       idx_type result = 1;
        col_type column = cellColumn(cell) + 1;
-       while (column < ncols && isPartOfMultiColumn(row, column)) {
-               ++result;
+       while (column < ncols && isPartOfMultiColumn(row, column))
                ++column;
-       }
-       return result;
+
+       return column - cellColumn(cell);
 }
 
 
-Tabular::idx_type Tabular::unsetMultiColumn(idx_type cell)
+Tabular::idx_type Tabular::rowSpan(idx_type cell) const
+{
+       row_type const nrows = row_info.size();
+       col_type const column = cellColumn(cell);
+       col_type row = cellRow(cell) + 1;
+       while (row < nrows && isPartOfMultiRow(row, column))
+               ++row;
+       
+       return row - cellRow(cell);
+}
+
+
+void Tabular::unsetMultiColumn(idx_type cell)
 {
        row_type const row = cellRow(cell);
-       col_type column = cellColumn(cell);
+       col_type const column = cellColumn(cell);
+       row_type const span = columnSpan(cell);
+       for (col_type c = 0; c < span; ++c)
+               cell_info[row][column + c].multicolumn = CELL_NORMAL;
+       updateIndexes();
+}
 
-       idx_type result = 0;
 
-       if (cell_info[row][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN) {
-               cell_info[row][column].multicolumn = CELL_NORMAL;
-               ++column;
-               while (column < column_info.size() &&
-                          cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
-               {
-                       cell_info[row][column].multicolumn = CELL_NORMAL;
-                       ++column;
-                       ++result;
-               }
-       }
+void Tabular::unsetMultiRow(idx_type cell)
+{
+       row_type const row = cellRow(cell);
+       col_type const column = cellColumn(cell);
+       row_type const span = rowSpan(cell);
+       for (row_type r = 0; r < span; ++r)
+               cell_info[row + r][column].multirow = CELL_NORMAL;
        updateIndexes();
-       return result;
 }
 
 
@@ -1578,25 +1708,31 @@ bool Tabular::isLastCell(idx_type cell) const
 
 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
 {
-       if (cellRow(cell) > 0)
-               return cell_info[cellRow(cell)-1][cellColumn(cell)].cellno;
-       return cell;
+       if (cellRow(cell) == 0)
+               return cell;
+       
+       col_type const col = cellColumn(cell);
+       row_type r = cellRow(cell) - 1;
+       while (r > 0 && cell_info[r][col].multirow == CELL_PART_OF_MULTIROW)
+               --r;
+
+       return cell_info[r][col].cellno;
 }
 
 
 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
 {
-       if (cellRow(cell) + 1 < row_info.size())
-               return cell_info[cellRow(cell)+1][cellColumn(cell)].cellno;
+       row_type const nextrow = cellRow(cell) + rowSpan(cell);
+       if (nextrow < row_info.size())
+               return cell_info[nextrow][cellColumn(cell)].cellno;
        return cell;
 }
 
 
-Tabular::idx_type Tabular::cellIndex(row_type row,
-                                              col_type column) const
+Tabular::idx_type Tabular::cellIndex(row_type row, col_type column) const
 {
-       BOOST_ASSERT(column != npos && column < column_info.size()
-               && row != npos && row < row_info.size());
+       LASSERT(column != npos && column < column_info.size()
+               && row != npos && row < row_info.size(), /**/);
        return cell_info[row][column].cellno;
 }
 
@@ -1741,13 +1877,16 @@ Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
 {
        idx_type i = getFirstCellInRow(row);
        if (what) {
-               setMultiColumn(i, column_info.size());
+               setMultiColumn(i, numberOfCellsInRow(row));
                setTopLine(i, false);
                setBottomLine(i, false);
                setLeftLine(i, false);
                setRightLine(i, false);
-       } else
+       } else {
                unsetMultiColumn(i);
+               // When unsetting a caption row, also all existing
+               // captions in this row must be dissolved.
+       }
        row_info[row].caption = what;
        return i;
 }
@@ -1759,6 +1898,15 @@ bool Tabular::ltCaption(row_type row) const
 }
 
 
+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)
@@ -1779,8 +1927,7 @@ void Tabular::setRowDescent(row_type row, int height)
 
 int Tabular::rowAscent(row_type row) const
 {
-       if (row >= row_info.size())
-               return 0;
+       LASSERT(row < row_info.size(), /**/);
        return row_info[row].ascent;
 }
 
@@ -1797,7 +1944,7 @@ int Tabular::height() const
        int height = 0;
        for (row_type row = 0; row < row_info.size(); ++row)
                height += rowAscent(row) + rowDescent(row) +
-                       getAdditionalHeight(row);
+                       interRowSpace(row);
        return height;
 }
 
@@ -1810,7 +1957,15 @@ bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
 }
 
 
-int Tabular::TeXTopHLine(odocstream & os, row_type row) const
+bool Tabular::isPartOfMultiRow(row_type row, col_type column) const
+{
+       LASSERT(row < row_info.size(), /**/);
+       LASSERT(column < column_info.size(), /**/);
+       return cell_info[row][column].multirow == CELL_PART_OF_MULTIROW;
+}
+
+
+int Tabular::TeXTopHLine(odocstream & os, row_type row, string const lang) const
 {
        // we only output complete row lines and the 1st row here, the rest
        // is done in Tabular::TeXBottomHLine(...)
@@ -1818,9 +1973,15 @@ int Tabular::TeXTopHLine(odocstream & os, row_type row) const
        // get for each column the topline (if any)
        col_type const ncols = column_info.size();
        vector<bool> topline;
-       int nset = 0;
+       col_type nset = 0;
        for (col_type c = 0; c < ncols; ++c) {
                topline.push_back(topLine(cellIndex(row, c)));
+               // If cell is part of a multirow and not the first cell of the
+               // multirow, no line must be drawn.
+               if (row != 0)
+                       if (isMultiRow(cellIndex(row, c))
+                               && isMultiRow(cellIndex(row - 1, c)))
+                                       topline[c] = false;
                if (topline[c])
                        ++nset;
        }
@@ -1839,7 +2000,14 @@ int Tabular::TeXTopHLine(odocstream & os, row_type row) const
        } else if (row == 0) {
                for (col_type c = 0; c < ncols; ++c) {
                        if (topline[c]) {
-                               os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 << '-';
+                               //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;
@@ -1852,7 +2020,7 @@ int Tabular::TeXTopHLine(odocstream & os, row_type row) const
 }
 
 
-int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
+int Tabular::TeXBottomHLine(odocstream & os, row_type row, string const lang) const
 {
        // we output bottomlines of row r and the toplines of row r+1
        // if the latter do not span the whole tabular
@@ -1865,11 +2033,19 @@ int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
        for (col_type c = 0; c < ncols; ++c) {
                bottomline.push_back(bottomLine(cellIndex(row, c)));
                topline.push_back(!lastrow && topLine(cellIndex(row + 1, c)));
+               // If cell is part of a multirow and not the last or first cell of the
+               // multirow, no line must be drawn.
+               if (!lastrow)
+                       if (isMultiRow(cellIndex(row, c))
+                               && isMultiRow(cellIndex(row + 1, c))) {
+                                       bottomline[c] = false;
+                                       topline[c] = false;
+                               }
                nextrowset &= topline[c];
        }
 
        // combine this row's bottom lines and next row's toplines if necessary
-       int nset = 0;
+       col_type nset = 0;
        for (col_type c = 0; c < ncols; ++c) {
                if (!nextrowset)
                        bottomline[c] = bottomline[c] || topline[c];
@@ -1885,12 +2061,18 @@ int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
                if (use_booktabs)
                        os << (lastrow ? "\\bottomrule" : "\\midrule");
                else
-                       os << "\\hline";
+                       os << "\\hline ";
        } else {
                for (col_type c = 0; c < ncols; ++c) {
                        if (bottomline[c]) {
-                               os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
-                                  << c + 1 << '-';
+                               //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;
@@ -1903,7 +2085,8 @@ int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
 }
 
 
-int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol) const
+int Tabular::TeXCellPreamble(odocstream & os, idx_type cell,
+                                                        bool & ismulticol, bool & ismultirow) const
 {
        int ret = 0;
        row_type const r = cellRow(cell);
@@ -1923,7 +2106,8 @@ int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol)
                && leftLine(cellIndex(r, nextcol));
        bool coldouble = colright && nextcolleft;
        bool celldouble = rightLine(cell) && nextcellleft;
-       ismulticol = isMultiColumn(cell) 
+
+       ismulticol = isMultiColumn(cell)
                || (c == 0 && colleft != leftLine(cell))
                || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
                || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
@@ -1983,7 +2167,21 @@ int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol)
                        // add extra vertical line if we want a double one
                        os << '|';
                os << "}{";
-               }
+               } // end if ismulticol
+
+       // we only need code for the first multirow cell
+       ismultirow = isMultiRow(cell);
+       if (ismultirow) {
+               os << "\\multirow{" << rowSpan(cell) << "}{";
+               if (!getPWidth(cell).zero())
+                       os << from_ascii(getPWidth(cell).asLatexString());
+               else
+                       // we need to set a default value
+                       // needs to be discussed
+                       os << "2.0cm";
+               os << "}{";
+               } // end if ismultirow
+
        if (getRotateCell(cell)) {
                os << "\\begin{sideways}\n";
                ++ret;
@@ -2024,7 +2222,8 @@ int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol)
 }
 
 
-int Tabular::TeXCellPostamble(odocstream & os, idx_type cell, bool ismulticol) const
+int Tabular::TeXCellPostamble(odocstream & os, idx_type cell,
+                                                         bool ismulticol, bool ismultirow) const
 {
        int ret = 0;
        row_type const r = cellRow(cell);
@@ -2042,7 +2241,7 @@ int Tabular::TeXCellPostamble(odocstream & os, idx_type cell, bool ismulticol) c
                os << "%\n\\end{sideways}";
                ++ret;
        }
-       if (ismulticol) {
+       if (ismulticol || ismultirow) {
                os << '}';
        }
        return ret;
@@ -2056,44 +2255,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 before 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 weird
+       if (haveLTFirstHead()) {
+               if (endfirsthead.topDL) {
                        os << "\\hline\n";
                        ++ret;
                }
                for (row_type i = 0; i < row_info.size(); ++i) {
-                       if (row_info[i].endhead) {
+                       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 (endfirsthead.empty && !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 < row_info.size(); ++i) {
-                       if (row_info[i].endfirsthead) {
+                       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
@@ -2113,7 +2323,7 @@ int Tabular::TeXLongtableHeaderFooter(odocstream & os,
                }
                os << "\\endfoot\n";
                ++ret;
-               if (endlastfoot.empty) {
+               if (endlastfoot.empty && !haveLTLastFoot()) {
                        os << "\\endlastfoot\n";
                        ++ret;
                }
@@ -2144,8 +2354,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;
 }
 
 
@@ -2153,7 +2364,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";
@@ -2173,10 +2390,14 @@ int Tabular::TeXRow(odocstream & os, row_type i,
                ++ret;
        }
        bool ismulticol = false;
+       bool ismultirow = false;
        for (col_type j = 0; j < column_info.size(); ++j) {
-               if (isPartOfMultiColumn(i, j))
+               if (isPartOfMultiRow(i, j))
+                       os << " & "; // we need to add a further column
+               if (isPartOfMultiColumn(i, j) || isPartOfMultiRow(i, j))
                        continue;
-               ret += TeXCellPreamble(os, cell, ismulticol);
+               cell = cellIndex(i, j);
+               ret += TeXCellPreamble(os, cell, ismulticol, ismultirow);
                shared_ptr<InsetTableCell> inset = cellInset(cell);
 
                Paragraph const & par = inset->paragraphs().front();
@@ -2199,21 +2420,27 @@ int Tabular::TeXRow(odocstream & os, row_type i,
                // pass to the OutputParams that we are in a cell and
                // which alignment we have set.
                // InsetNewline needs this context information.
-               OutputParams newrp = runparams;
+               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 << '}';
 
-               ret += TeXCellPostamble(os, cell, ismulticol);
-               if (!isLastCellInRow(cell)) { // not last cell in row
+               ret += TeXCellPostamble(os, cell, ismulticol, ismultirow);
+               if (cell != getLastCellInRow(i)) { // not last cell in row
                        os << " & ";
                }
-               ++cell;
        }
-       os << "\\tabularnewline";
+       if (row_info[i].caption && !endfirsthead.empty && !haveLTFirstHead())
+               // if no first header and no empty first header is used,
+               // the caption needs to be terminated by \endfirsthead
+               // (bug 6057)
+               os << "\\endfirsthead";
+       else
+               os << "\\tabularnewline";
        if (row_info[i].bottom_space_default) {
                if (use_booktabs)
                        os << "\\addlinespace";
@@ -2228,7 +2455,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";
@@ -2262,10 +2492,33 @@ int Tabular::latex(odocstream & os, OutputParams const & runparams) const
                os << "\\begin{sideways}\n";
                ++ret;
        }
-       if (is_long_tabular)
-               os << "\\begin{longtable}{";
-       else
-               os << "\\begin{tabular}{";
+       if (is_long_tabular) {
+               os << "\\begin{longtable}";
+               switch (longtabular_alignment) {
+               case LYX_LONGTABULAR_ALIGN_LEFT:
+                       os << "[l]";
+                       break;
+               case LYX_LONGTABULAR_ALIGN_CENTER:
+                       break;
+               case LYX_LONGTABULAR_ALIGN_RIGHT:
+                       os << "[r]";
+                       break;
+               }
+       } else {
+               os << "\\begin{tabular}";
+               switch (tabular_valignment) {
+               case LYX_VALIGN_TOP:
+                       os << "[t]";
+                       break;
+               case LYX_VALIGN_MIDDLE:
+                       break;
+               case LYX_VALIGN_BOTTOM:
+                       os << "[b]";
+                       break;
+               }
+       }
+       
+       os << "{";
 
        for (col_type i = 0; i < column_info.size(); ++i) {
                if (columnLeftLine(i))
@@ -2445,6 +2698,18 @@ int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
        //+                      Long Tabular case                             +
        //+---------------------------------------------------------------------
 
+       // output caption info
+       if (haveLTCaption()) {
+               os << "<caption>\n";
+               ++ret;
+               for (row_type i = 0; i < row_info.size(); ++i) {
+                       if (row_info[i].caption) {
+                               ret += docbookRow(os, i, runparams);
+                       }
+               }
+               os << "</caption>\n";
+               ++ret;
+       }
        // output header info
        if (haveLTHead() || haveLTFirstHead()) {
                os << "<thead>\n";
@@ -2494,11 +2759,79 @@ int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
 }
 
 
+docstring Tabular::xhtmlRow(XHTMLStream & xs, row_type row,
+                          OutputParams const & runparams) const
+{
+       docstring ret;
+       idx_type cell = getFirstCellInRow(row);
+
+       xs << html::StartTag("tr");
+       for (col_type j = 0; j < column_info.size(); ++j) {
+               if (isPartOfMultiColumn(row, j))
+                       continue;
+
+               stringstream attr;
+               attr << "align='";
+               switch (getAlignment(cell)) {
+               case LYX_ALIGN_LEFT:
+                       attr << "left";
+                       break;
+               case LYX_ALIGN_RIGHT:
+                       attr << "right";
+                       break;
+               default:
+                       attr << "center";
+                       break;
+               }
+               attr << "'";
+               attr << " valign='";
+               switch (getVAlignment(cell)) {
+               case LYX_VALIGN_TOP:
+                       attr << "top";
+                       break;
+               case LYX_VALIGN_BOTTOM:
+                       attr << "bottom";
+                       break;
+               case LYX_VALIGN_MIDDLE:
+                       attr << "middle";
+               }
+               attr << "'";
+
+               if (isMultiColumn(cell))
+                       attr << " colspan='" << columnSpan(cell) << "'";
+
+               xs << html::StartTag("td", attr.str());
+               ret += cellInset(cell)->xhtml(xs, runparams);
+               xs << html::EndTag("td");
+               ++cell;
+       }
+       xs << html::EndTag("tr");
+       return ret;
+}
+
+
+docstring Tabular::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
+{
+       docstring ret;
+       // It's unclear to me if we need to mess with the long table stuff. 
+       // We can borrow that too from docbook, if so.
+
+       xs << html::StartTag("tbody");
+       for (row_type i = 0; i < row_info.size(); ++i) {
+               if (isValidRow(i)) {
+                       ret += xhtmlRow(xs, i, runparams);
+               }
+       }
+       xs << html::EndTag("tbody");
+       return ret;
+}
+
+
 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
                                   vector<unsigned int> const & clen) const
 {
        idx_type const fcell = getFirstCellInRow(row);
-       idx_type const n = numberOfCellsInRow(fcell) + fcell;
+       idx_type const n = numberOfCellsInRow(row) + fcell;
        idx_type tmp = 0;
 
        for (idx_type i = fcell; i < n; ++i) {
@@ -2546,7 +2879,7 @@ bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
                                      vector<unsigned int> const & clen) const
 {
        idx_type const fcell = getFirstCellInRow(row);
-       idx_type const n = numberOfCellsInRow(fcell) + fcell;
+       idx_type const n = numberOfCellsInRow(row) + fcell;
        idx_type tmp = 0;
 
        for (idx_type i = fcell; i < n; ++i) {
@@ -2734,6 +3067,8 @@ void Tabular::validate(LaTeXFeatures & features) const
        if (needRotating())
                features.require("rotating");
        for (idx_type cell = 0; cell < numberofcells; ++cell) {
+               if (isMultiRow(cell))
+                       features.require("multirow");
                if (getVAlignment(cell) != LYX_VALIGN_TOP
                    || !getPWidth(cell).zero())
                        features.require("array");
@@ -2763,8 +3098,8 @@ Tabular::BoxType Tabular::useParbox(idx_type cell) const
 //
 /////////////////////////////////////////////////////////////////////
 
-InsetTableCell::InsetTableCell(Buffer & buf)
-       : InsetText(buf), isFixedWidth(false),
+InsetTableCell::InsetTableCell(Buffer * buf)
+       : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
          contentAlign(LYX_ALIGN_CENTER)
 {}
 
@@ -2818,6 +3153,14 @@ docstring InsetTableCell::asString(bool intoInsets)
 }
 
 
+docstring InsetTableCell::xhtml(XHTMLStream & xs, OutputParams const & rp) const
+{
+       if (!isFixedWidth)
+               return InsetText::insetAsXHTML(xs, rp, InsetText::JustText);
+       return InsetText::xhtml(xs, rp);
+}
+
+
 
 /////////////////////////////////////////////////////////////////////
 //
@@ -2825,12 +3168,11 @@ docstring InsetTableCell::asString(bool intoInsets)
 //
 /////////////////////////////////////////////////////////////////////
 
-InsetTabular::InsetTabular(Buffer & 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), 
+       : Inset(buf), tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
        rowselect_(false), colselect_(false)
 {
-       setBuffer(buf); // FIXME: remove later
 }
 
 
@@ -2855,7 +3197,8 @@ void InsetTabular::setBuffer(Buffer & buf)
 
 bool InsetTabular::insetAllowed(InsetCode code) const
 {
-       if (code == MATHMACRO_CODE)
+       if (code == MATHMACRO_CODE
+               || (code == CAPTION_CODE && !tabular.is_long_tabular))
                return false;
 
        return true;
@@ -2902,11 +3245,10 @@ int InsetTabular::rowFromY(Cursor & cur, int y) const
        int h = yo(cur.bv()) - tabular.rowAscent(0);
        size_t nrows = tabular.row_info.size();
        row_type r = 0;
-       for (; r < nrows && y > h; ++r) {
-               h += tabular.rowAscent(r);
-               h += tabular.rowDescent(r);
-               h += tabular.getAdditionalHeight(r);
-       }
+       for (; r < nrows && y > h; ++r)
+               h += tabular.rowAscent(r) + tabular.rowDescent(r)
+               + tabular.interRowSpace(r);
+
        return r - 1;
 }
 
@@ -2932,14 +3274,15 @@ void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
                LASSERT(false, /**/);
        }
 
-       row_type i = 0;
-       for (idx_type cell = 0; i < tabular.row_info.size(); ++i) {
+       for (row_type i = 0; i < tabular.row_info.size(); ++i) {
                int maxAsc = 0;
                int maxDesc = 0;
                for (col_type j = 0; j < tabular.column_info.size(); ++j) {
-                       if (tabular.isPartOfMultiColumn(i, j))
-                               // Multicolumn cell, but not first one
+                       if (tabular.isPartOfMultiColumn(i, j)
+                               || tabular.isPartOfMultiRow(i, j))
+                               // multicolumn or multirow cell, but not first one
                                continue;
+                       idx_type const cell = tabular.cellIndex(i, j);
                        Dimension dim;
                        MetricsInfo m = mi;
                        Length p_width;
@@ -2956,7 +3299,6 @@ void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
                        tabular.setCellWidth(cell, dim.wid);
                        maxAsc  = max(maxAsc, dim.asc);
                        maxDesc = max(maxDesc, dim.des);
-                       ++cell;
                }
                int const top_space = tabular.row_info[i].top_space_default ?
                        default_line_space :
@@ -2973,58 +3315,79 @@ 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;
+       x += scx_ + ADD_TO_TABULAR_WIDTH;
+
        BufferView * bv = pi.base.bv;
+       Cursor & cur = pi.base.bv->cursor();
+       resetPos(cur);
 
-       // FIXME: As the full backrgound is painted in drawSelection(),
+       // FIXME: As the full background is painted in drawSelection(),
        // we have no choice but to do a full repaint for the Text cells.
        pi.full_repaint = true;
 
-       resetPos(bv->cursor());
-
-       x += scx_;
-       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.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.column_info.size(); ++j) {
                        if (tabular.isPartOfMultiColumn(i, j))
                                continue;
+                       
+                       idx = tabular.cellIndex(i, j);
+                       
+                       if (tabular.isPartOfMultiRow(i, j)) {
+                               nx += tabular.columnWidth(idx);
+                               continue;
+                       }
+
                        if (first_visible_cell == Tabular::npos)
                                first_visible_cell = idx;
 
-                       int const cx = nx + tabular.getBeginningOfTextInCell(idx);
+                       pi.selected |= isCellSelected(cur, i, j);
+                       int const cx = nx + tabular.textHOffset(idx);
+                       int const cy = y  + tabular.textVOffset(idx);
                        // Cache the Inset position.
                        bv->coordCache().insets().add(cell(idx).get(), cx, y);
-                       if (nx + tabular.columnWidth(idx) < 0
-                           || nx > bv->workWidth()
-                           || y + d < 0
-                           || y - a > bv->workHeight()) {
-                               pi.pain.setDrawingEnabled(false);
-                               cell(idx)->draw(pi, cx, y);
-                               drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
-                               pi.pain.setDrawingEnabled(original_drawing_state);
-                       } else {
-                               cell(idx)->draw(pi, cx, y);
-                               drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
-                       }
+                       cell(idx)->draw(pi, cx, cy);
+                       drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
                        nx += tabular.columnWidth(idx);
-                       ++idx;
+                       pi.selected = original_selection_state;
                }
 
                if (i + 1 < tabular.row_info.size())
-                       y += d + tabular.rowAscent(i + 1) +
-                               tabular.getAdditionalHeight(i + 1);
+                       y += tabular.rowDescent(i) + tabular.rowAscent(i + 1)
+                            + tabular.interRowSpace(i + 1);
        }
 }
 
@@ -3032,6 +3395,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;
 
@@ -3042,7 +3406,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;
@@ -3051,84 +3415,78 @@ 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 (cur.selIsMultiCell()) {
-               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.row_info.size(); ++j) {
-                       int const a = tabular.rowAscent(j);
-                       int const h = a + tabular.rowDescent(j);
+               for (row_type r = 0; r < tabular.row_info.size(); ++r) {
                        int xx = x;
-                       y += tabular.getAdditionalHeight(j);
-                       for (col_type i = 0; i < tabular.column_info.size(); ++i) {
-                               if (tabular.isPartOfMultiColumn(j, i))
+                       for (col_type c = 0; c < tabular.column_info.size(); ++c) {
+                               if (tabular.isPartOfMultiColumn(r, c))
+                                       continue;
+
+                               idx_type const cell = tabular.cellIndex(r, c);
+
+                               if (tabular.isPartOfMultiRow(r, c)) {
+                                       xx += tabular.columnWidth(cell);
                                        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);
+                               int const h = tabular.rowHeight(cell);
+                               if (isCellSelected(cur, r, c))
+                                       pi.pain.fillRectangle(xx, y, w, h, Color_selection);
                                xx += w;
                        }
-                       y += h;
+                       if (r + 1 < tabular.row_info.size())
+                               y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
+                                    + tabular.interRowSpace(r + 1);
                }
 
        } else {
                x += cellXPos(cur.idx());
-               x += tabular.getBeginningOfTextInCell(cur.idx());
+               x += tabular.textHOffset(cur.idx());
                cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
        }
 }
 
 
 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);
+       y = y - tabular.rowAscent(row);
+       int const w = tabular.columnWidth(cell);
+       int const h = tabular.rowHeight(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)) {
                on_off = !tabular.topLine(cell);
-               pain.line(x, y - tabular.rowAscent(row),
-                         x2, y -  tabular.rowAscent(row),
-                         on_off ? onoffcol : col,
-                         on_off ? Painter::line_onoffdash : Painter::line_solid);
+               pain.line(x, y, x + w, y,
+                       on_off ? onoffcol : col,
+                       on_off ? Painter::line_onoffdash : Painter::line_solid);
        }
        on_off = !tabular.bottomLine(cell);
-       pain.line(x, y + tabular.rowDescent(row),
-                 x2, y + tabular.rowDescent(row),
-                 on_off ? onoffcol : col,
-                 on_off ? Painter::line_onoffdash : Painter::line_solid);
+       pain.line(x, y + h, x + w, y + h,
+               on_off ? onoffcol : col,
+               on_off ? Painter::line_onoffdash : Painter::line_solid);
        if (!tabular.leftAlreadyDrawn(cell)) {
                on_off = !tabular.leftLine(cell);
-               pain.line(x, y -  tabular.rowAscent(row),
-                         x, y +  tabular.rowDescent(row),
-                         on_off ? onoffcol : col,
-                         on_off ? Painter::line_onoffdash : Painter::line_solid);
+               pain.line(x, y, x, y + h,
+                       on_off ? onoffcol : col,
+                       on_off ? Painter::line_onoffdash : Painter::line_solid);
        }
        on_off = !tabular.rightLine(cell);
-       pain.line(x2 - tabular.getAdditionalWidth(cell),
-                 y -  tabular.rowAscent(row),
-                 x2 - tabular.getAdditionalWidth(cell),
-                 y +  tabular.rowDescent(row),
-                 on_off ? onoffcol : col,
-                 on_off ? Painter::line_onoffdash : Painter::line_solid);
-}
-
-
-docstring InsetTabular::editMessage() const
-{
-       return _("Opened table");
+       pain.line(x + w - tabular.interColumnSpace(cell), y,
+               x + w - tabular.interColumnSpace(cell), y + h,
+               on_off ? onoffcol : col,
+               on_off ? Painter::line_onoffdash : Painter::line_solid);
 }
 
 
@@ -3136,7 +3494,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))
@@ -3153,16 +3511,17 @@ void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
                cur.pit() = 0;
                cur.pos() = cur.lastpos(); // FIXME crude guess
        }
+       cur.setCurrentFont();
        // FIXME: this accesses the position cache before it is initialized
        //resetPos(cur);
        //cur.bv().fitCursor();
 }
 
 
-void InsetTabular::updateLabels(ParIterator const & it)
+void InsetTabular::updateLabels(ParIterator const & it, UpdateType utype)
 {
        // 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.is_long_tabular)
                cnts.current_float("table");
@@ -3171,7 +3530,7 @@ void InsetTabular::updateLabels(ParIterator const & it)
        it2.forwardPos();
        size_t const end = it2.nargs();
        for ( ; it2.idx() < end; it2.top().forwardIdx())
-               lyx::updateLabels(buffer(), it2);
+               buffer().updateLabels(it2, utype);
 
        //reset afterwards
        if (tabular.is_long_tabular)
@@ -3179,6 +3538,16 @@ void InsetTabular::updateLabels(ParIterator const & it)
 }
 
 
+void InsetTabular::addToToc(DocIterator const & cpit)
+{
+       DocIterator dit = cpit;
+       dit.forwardPos();
+       size_t const end = dit.nargs();
+       for ( ; dit.idx() < end; dit.top().forwardIdx())
+               cell(dit.idx())->addToToc(dit);
+}
+
+
 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
 {
        LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
@@ -3199,7 +3568,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;
@@ -3214,7 +3583,7 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                        cur.resetAnchor();
                        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;
@@ -3247,7 +3616,7 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                                cur.pit() = 0;
                                cur.pos() = 0;
                                bvcur.setCursor(cur);
-                               bvcur.selection() = true;
+                               bvcur.setSelection(true);
                                break;
                        }
                        // select (additional) column
@@ -3259,7 +3628,7 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                                cur.pit() = 0;
                                cur.pos() = 0;
                                bvcur.setCursor(cur);
-                               bvcur.selection() = true;
+                               bvcur.setSelection(true);
                                break;
                        }
                        // only update if selection changes
@@ -3268,12 +3637,12 @@ 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() = 0;
-                               bvcur.pos() = 0;
+                               bvcur.pit() = bvcur.lastpit();
+                               bvcur.pos() = bvcur.lastpos();
                        }
                }
                break;
@@ -3285,12 +3654,12 @@ 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:
@@ -3321,32 +3690,53 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                // LEFT or RIGHT commands --- the interpretation will depend on the 
                // table's direction.
                else {
-                       bool right = (cmd.action == LFUN_CHAR_RIGHT
-                                                       || cmd.action == LFUN_CHAR_RIGHT_SELECT);
-                       next_cell = (isRightToLeft(cur) != right);
+                       bool const right = cmd.action == LFUN_CHAR_RIGHT
+                               || cmd.action == LFUN_CHAR_RIGHT_SELECT;
+                       next_cell = isRightToLeft(cur) != right;
                        
-                       if (lyxrc.visual_cursor) {
+                       if (lyxrc.visual_cursor)
                                entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
-                       }
 
-                       if (right)
-                               finish_lfun = LFUN_FINISHED_RIGHT;
-                       else
-                               finish_lfun = LFUN_FINISHED_LEFT;
+                       finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
                }
 
-               // if we don't have a multicell selection...
-               if (!cur.selIsMultiCell() ||
-                 // ...or we're not doing some LFUN_*_SELECT thing, anyway...
-                   (cmd.action != LFUN_CHAR_FORWARD_SELECT &&
-                    cmd.action != LFUN_CHAR_BACKWARD_SELECT &&
-                    cmd.action != LFUN_CHAR_RIGHT_SELECT &&
-                    cmd.action != LFUN_CHAR_LEFT_SELECT)) {
+               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));
+
+                       bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
+
                        // ...try to dispatch to the cell's inset.
                        cell(cur.idx())->dispatch(cur, cmd);
-                       if (cur.result().dispatched()) 
+
+                       // 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;
                }
+
                // move to next/prev cell, as appropriate
                // note that we will always do this if we're selecting and we have
                // a multicell selection
@@ -3367,35 +3757,48 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
 
        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.
+                       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());
+                               cur.setCurrentFont();
                        }
+               }
                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();
+                       cur.setCurrentFont();
+                       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();
@@ -3404,11 +3807,19 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                                ParagraphMetrics const & pm =
                                        tm.parMetrics(cur.lastpit());
                                cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
+                               cur.setCurrentFont();
                        }
+               }
                if (sl == cur.top()) {
                        cmd = FuncRequest(LFUN_UP);
                        cur.undispatched();
                }
+               if (cur.selIsMultiCell()) {
+                       cur.pit() = 0;
+                       cur.pos() = cur.lastpos();
+                       cur.setCurrentFont();
+                       return;
+               }
                break;
 
 //     case LFUN_SCREEN_DOWN: {
@@ -3461,23 +3872,24 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
 
        // insert file functions
        case LFUN_FILE_INSERT_PLAINTEXT_PARA:
-       case LFUN_FILE_INSERT_PLAINTEXT: {
+       case LFUN_FILE_INSERT_PLAINTEXT:
                // FIXME UNICODE
-               docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
-                       FileName(to_utf8(cmd.argument())));
-               if (tmpstr.empty())
-                       break;
-               cur.recordUndoInset(INSERT_UNDO);
-               if (insertPlaintextString(cur.bv(), tmpstr, false)) {
-                       // content has been replaced,
-                       // so cursor might be invalid
-                       cur.pos() = cur.lastpos();
-                       cur.pit() = cur.lastpit();
-                       bvcur.setCursor(cur);
-               } else
-                       cur.undispatched();
+               if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
+                       docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
+                               FileName(to_utf8(cmd.argument())));
+                       if (tmpstr.empty())
+                               break;
+                       cur.recordUndoInset(INSERT_UNDO);
+                       if (insertPlaintextString(cur.bv(), tmpstr, false)) {
+                               // content has been replaced,
+                               // so cursor might be invalid
+                               cur.pos() = cur.lastpos();
+                               cur.pit() = cur.lastpit();
+                               bvcur.setCursor(cur);
+                       } else
+                               cur.undispatched();
+               }
                break;
-       }
 
        case LFUN_CUT:
                if (cur.selIsMultiCell()) {
@@ -3485,18 +3897,24 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                                cur.recordUndoInset(DELETE_UNDO);
                                cutSelection(cur);
                        }
-               }
-               else
+               } else
                        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 (cur.selIsMultiCell()) {
                        cur.recordUndoInset(DELETE_UNDO);
                        cutSelection(cur);
-               }
-               else
+               } else
                        cell(cur.idx())->dispatch(cur, cmd);
                break;
 
@@ -3537,11 +3955,12 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
 
        case LFUN_PASTE:
                if (!tabularStackDirty()) {
-                       cell(cur.idx())->dispatch(cur, cmd);
+                       if (!cur.selIsMultiCell())
+                               cell(cur.idx())->dispatch(cur, cmd);
                        break;
                }
                if (theClipboard().isInternal() ||
-                   !theClipboard().hasInternal() && theClipboard().hasLyXContents()) {
+                   (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
                        cur.recordUndoInset(INSERT_UNDO);
                        pasteClipboard(cur);
                }
@@ -3560,6 +3979,9 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
        case LFUN_TEXTSTYLE_UPDATE:
        case LFUN_FONT_SIZE:
        case LFUN_FONT_UNDERLINE:
+       case LFUN_FONT_STRIKEOUT:
+       case LFUN_FONT_UULINE:
+       case LFUN_FONT_UWAVE:
        case LFUN_LANGUAGE:
        case LFUN_WORD_CAPITALIZE:
        case LFUN_WORD_UPCASE:
@@ -3590,6 +4012,12 @@ void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
                        cell(cur.idx())->dispatch(cur, cmd);
                        break;
                }
+
+       case LFUN_INSET_SETTINGS:
+               // relay this lfun to Inset, not to the cell.
+               Inset::doDispatch(cur, cmd);
+               break;
+
        default:
                // we try to handle this event in the insets dispatch function.
                cell(cur.idx())->dispatch(cur, cmd);
@@ -3636,7 +4064,8 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                case Tabular::SET_PWIDTH:
                case Tabular::SET_MPWIDTH:
                case Tabular::SET_SPECIAL_COLUMN:
-               case Tabular::SET_SPECIAL_MULTI:
+               case Tabular::SET_SPECIAL_MULTICOLUMN:
+               case Tabular::SET_SPECIAL_MULTIROW:
                case Tabular::APPEND_ROW:
                case Tabular::APPEND_COLUMN:
                case Tabular::DELETE_ROW:
@@ -3650,10 +4079,21 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                        return true;
 
                case Tabular::MULTICOLUMN:
-                       status.setEnabled(sel_row_start == sel_row_end);
+                       // If a row is set as longtable caption, it must not be allowed
+                       // to unset that this row is a multicolumn.
+                       status.setEnabled(sel_row_start == sel_row_end
+                               && !tabular.ltCaption(tabular.cellRow(cur.idx())));
                        status.setOnOff(tabular.isMultiColumn(cur.idx()));
                        break;
 
+               case Tabular::MULTIROW:
+                       // If a row is set as longtable caption, it must not be allowed
+                       // to unset that this row is a multirow.
+                       status.setEnabled(sel_col_start == sel_col_end
+                               && !tabular.ltCaption(tabular.cellRow(cur.idx())));
+                       status.setOnOff(tabular.isMultiRow(cur.idx()));
+                       break;
+
                case Tabular::SET_ALL_LINES:
                case Tabular::UNSET_ALL_LINES:
                case Tabular::SET_BORDER_LINES:
@@ -3737,6 +4177,32 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                        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::LONGTABULAR_ALIGN_LEFT:
+                       status.setOnOff(tabular.longtabular_alignment 
+                               == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
+                       break;
+               case Tabular::LONGTABULAR_ALIGN_CENTER:
+                       status.setOnOff(tabular.longtabular_alignment 
+                               == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
+                       break;
+               case Tabular::LONGTABULAR_ALIGN_RIGHT:
+                       status.setOnOff(tabular.longtabular_alignment 
+                               == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
+                       break;
+
                case Tabular::UNSET_ROTATE_TABULAR:
                        status.setOnOff(!tabular.rotate);
                        break;
@@ -3756,15 +4222,21 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                        status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
                        break;
 
+               // every row can only be one thing:
+               // either a footer or header or caption
                case Tabular::SET_LTFIRSTHEAD:
-                       status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
+                       status.setEnabled(sel_row_start == sel_row_end
+                               && !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.ltCaption(sel_row_start));
                        status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
                        break;
 
@@ -3773,6 +4245,8 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                        break;
 
                case Tabular::SET_LTFOOT:
+                       status.setEnabled(sel_row_start == sel_row_end
+                               && !tabular.ltCaption(sel_row_start));
                        status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
                        break;
 
@@ -3781,19 +4255,28 @@ 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.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;
 
+               // only one row can be the caption
                case Tabular::TOGGLE_LTCAPTION:
-                       status.setEnabled(sel_row_start == sel_row_end);
+                       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)
+                               && (!tabular.haveLTCaption()
+                                       || tabular.ltCaption(sel_row_start)));
                        status.setOnOff(tabular.ltCaption(sel_row_start));
                        break;
 
@@ -3835,6 +4318,7 @@ 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 (cur.selIsMultiCell()) {
@@ -3859,17 +4343,28 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
                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.setEnabled(true);
+                       if (cur.selIsMultiCell()) {
+                               row_type rs, re;
+                               col_type cs, ce;
+                               getSelection(cur, rs, re, cs, ce);
+                               if (paste_tabular && paste_tabular->column_info.size() == ce - cs + 1
+                                         && paste_tabular->row_info.size() == re - rs + 1)
+                                       status.setEnabled(true);        
+                               else {
+                                       status.setEnabled(false);
+                                       status.message(_("Selection size should match clipboard content."));
+                               }
+                       } else
+                               status.setEnabled(true);
                        return true;
-               } 
+               }
                return cell(cur.idx())->getStatus(cur, cmd, status);
 
+       case LFUN_INSET_SETTINGS:
+               // relay this lfun to Inset, not to the cell.
+               return Inset::getStatus(cur, cmd, status);
+
        case LFUN_INSET_MODIFY:
                if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
                        status.setEnabled(true);
@@ -3884,6 +4379,24 @@ bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
 }
 
 
+Inset::DisplayType InsetTabular::display() const
+{
+               if (tabular.is_long_tabular) {
+                       switch (tabular.longtabular_alignment) {
+                       case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
+                               return AlignLeft;
+                       case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
+                               return AlignCenter;
+                       case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
+                               return AlignRight;
+                       default:
+                               return AlignCenter;
+                       }
+               } else
+                       return Inline;
+}
+
+
 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
 {
        return tabular.latex(os, runparams);
@@ -3926,9 +4439,29 @@ int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
 }
 
 
+docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
+{
+       // FIXME XHTML
+       // It'd be better to be able to get this from an InsetLayout, but at present
+       // InsetLayouts do not seem really to work for things that aren't InsetTexts.
+       xs << html::StartTag("table");
+       docstring ret = tabular.xhtml(xs, rp);
+       xs << html::EndTag("table");
+       return ret;
+}
+
+
 void InsetTabular::validate(LaTeXFeatures & features) const
 {
        tabular.validate(features);
+       // FIXME XHTML
+       // It'd be better to be able to get this from an InsetLayout, but at present
+       // InsetLayouts do not seem really to work for things that aren't InsetTexts.
+       if (features.runparams().flavor == OutputParams::HTML)
+               features.addPreambleSnippet("<style type=\"text/css\">\n"
+      "table { border: 1px solid black; display: inline-block; }\n"
+      "td { border: 1px solid black; padding: 0.5ex; }\n"
+      "</style>");
 }
 
 
@@ -3949,27 +4482,27 @@ void InsetTabular::cursorPos(BufferView const & bv,
 {
        cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
 
-       // y offset     correction
        int const row = tabular.cellRow(sl.idx());
+       int const col = tabular.cellColumn(sl.idx());
+
+       // y offset     correction
        for (int i = 0; i <= row; ++i) {
+               if (tabular.isPartOfMultiRow(i, col))
+                       continue;
                if (i != 0) {
                        y += tabular.rowAscent(i);
-                       y += tabular.getAdditionalHeight(i);
+                       y += tabular.interRowSpace(i);
                }
                if (i != row)
                        y += tabular.rowDescent(i);
        }
+       y += tabular.textVOffset(sl.idx());
 
        // x offset correction
-       int const col = tabular.cellColumn(sl.idx());
-       int idx = tabular.cellIndex(row, 0);
-       for (int j = 0; j < col; ++j) {
-               if (tabular.isPartOfMultiColumn(row, j))
-                       continue;
-               x += tabular.columnWidth(idx);
-               ++idx;
-       }
-       x += tabular.getBeginningOfTextInCell(idx);
+       for (int c = 0; c < col; ++c)
+               x += tabular.column_info[c].width;
+       
+       x += tabular.textHOffset(sl.idx());
        x += ADD_TO_TABULAR_WIDTH;
        x += scx_;
 }
@@ -3981,11 +4514,11 @@ int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
        int yy = 0;
        Inset const & inset = *tabular.cellInset(cell);
        Point o = bv.coordCache().getInsets().xy(&inset);
-       int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
+       int const xbeg = o.x_ - tabular.textHOffset(cell);
        int const xend = xbeg + tabular.columnWidth(cell);
        row_type const row = tabular.cellRow(cell);
-       int const ybeg = o.y_ - tabular.rowAscent(row) -
-                        tabular.getAdditionalHeight(row);
+       int const ybeg = o.y_ - tabular.rowAscent(row)
+               - tabular.interRowSpace(row);
        int const yend = o.y_ + tabular.rowDescent(row);
 
        if (x < xbeg)
@@ -4009,7 +4542,7 @@ 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);
@@ -4043,12 +4576,9 @@ InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int
 
 int InsetTabular::cellXPos(idx_type const cell) const
 {
-       idx_type c = cell;
-
-       for (; !tabular.isFirstCellInRow(c); --c)
-               ;
+       col_type col = tabular.cellColumn(cell);
        int lx = 0;
-       for (; c < cell; ++c)
+       for (col_type c = 0; c < col; ++c)
                lx += tabular.columnWidth(c);
 
        return lx;
@@ -4087,25 +4617,42 @@ void InsetTabular::resetPos(Cursor & cur) const
 
 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
 {
+       row_type const row = tabular.cellRow(cur.idx());
+       col_type const col = tabular.cellColumn(cur.idx());
+
        if (isRightToLeft(cur)) {
-               if (tabular.isFirstCellInRow(cur.idx())) {
-                       row_type const row = tabular.cellRow(cur.idx());
+               if (tabular.cellColumn(cur.idx()) == 0) {
                        if (row == tabular.row_info.size() - 1)
                                return;
                        cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
                } else {
                        if (cur.idx() == 0)
                                return;
-                       --cur.idx();
+                       if (col == 0)
+                               cur.idx() = tabular.getLastCellInRow(row - 1);
+                       else
+                               cur.idx() = tabular.cellIndex(row, col - 1);
                }
        } else {
                if (tabular.isLastCell(cur.idx()))
                        return;
-               ++cur.idx();
+               if (cur.idx() == tabular.getLastCellInRow(row))
+                       cur.idx() = tabular.cellIndex(row + 1, 0);
+               else
+                       cur.idx() = tabular.cellIndex(row, col + 1);
        }
+
+       cur.boundary(false);
+
+       if (cur.selIsMultiCell()) {
+               cur.pit() = cur.lastpit();
+               cur.pos() = cur.lastpos();
+               resetPos(cur);
+               return;
+       }
+
        cur.pit() = 0;
        cur.pos() = 0;
-       cur.boundary(false);
 
        // in visual mode, place cursor at extreme left or right
        
@@ -4122,16 +4669,18 @@ void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
                break;
 
        }
-
+       cur.setCurrentFont();
        resetPos(cur);
 }
 
 
 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
 {
+       row_type const row = tabular.cellRow(cur.idx());
+       col_type const col = tabular.cellColumn(cur.idx());
+
        if (isRightToLeft(cur)) {
-               if (tabular.isLastCellInRow(cur.idx())) {
-                       row_type const row = tabular.cellRow(cur.idx());
+               if (cur.idx() == tabular.getLastCellInRow(row)) {
                        if (row == 0)
                                return;
                        cur.idx() = tabular.getFirstCellInRow(row);
@@ -4139,13 +4688,27 @@ void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
                } else {
                        if (tabular.isLastCell(cur.idx()))
                                return;
-                       ++cur.idx();
+                       if (cur.idx() == tabular.getLastCellInRow(row))
+                               cur.idx() = tabular.cellIndex(row + 1, 0);
+                       else
+                               cur.idx() = tabular.cellIndex(row, col + 1);
                }
        } else {
                if (cur.idx() == 0) // first cell
                        return;
-               --cur.idx();
+               if (col == 0)
+                       cur.idx() = tabular.getLastCellInRow(row - 1);
+               else
+                       cur.idx() = tabular.cellIndex(row, col - 1);
+       }
+
+       if (cur.selIsMultiCell()) {
+               cur.pit() = cur.lastpit();
+               cur.pos() = cur.lastpos();
+               resetPos(cur);
+               return;
        }
+
        cur.pit() = cur.lastpit();
        cur.pos() = cur.lastpos();
 
@@ -4164,7 +4727,7 @@ void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
                break;
 
        }
-
+       cur.setCurrentFont();
        resetPos(cur);
 }
 
@@ -4302,7 +4865,7 @@ void InsetTabular::tabularFeatures(Cursor & cur,
                break;
 
        case Tabular::SET_SPECIAL_COLUMN:
-       case Tabular::SET_SPECIAL_MULTI:
+       case Tabular::SET_SPECIAL_MULTICOLUMN:
                tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
                break;
 
@@ -4325,7 +4888,7 @@ void InsetTabular::tabularFeatures(Cursor & cur,
                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:
@@ -4336,7 +4899,7 @@ void InsetTabular::tabularFeatures(Cursor & cur,
                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:
@@ -4418,12 +4981,36 @@ void InsetTabular::tabularFeatures(Cursor & cur,
                // we have a selection so this means we just add all this
                // cells to form a multicolumn cell
                idx_type const s_start = cur.selBegin().idx();
-               idx_type const s_end = cur.selEnd().idx();
-               tabular.setMultiColumn(s_start, s_end - s_start + 1);
+               row_type const col_start = tabular.cellColumn(s_start);
+               row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
+               tabular.setMultiColumn(s_start, col_end - col_start + 1);
                cur.idx() = s_start;
                cur.pit() = 0;
                cur.pos() = 0;
-               cur.selection() = false;
+               cur.setSelection(false);
+               break;
+       }
+       
+       case Tabular::MULTIROW: {
+               if (!cur.selection()) {
+                       // just multirow for one single cell
+                       // check whether we are completely in a multirow
+                       if (tabular.isMultiRow(cur.idx()))
+                               tabular.unsetMultiRow(cur.idx());
+                       else
+                               tabular.setMultiRow(cur.idx(), 1);
+                       break;
+               }
+               // we have a selection so this means we just add all this
+               // cells to form a multirow cell
+               idx_type const s_start = cur.selBegin().idx();
+               row_type const row_start = tabular.cellRow(s_start);
+               row_type const row_end = tabular.cellRow(cur.selEnd().idx());
+               tabular.setMultiRow(s_start, row_end - row_start + 1);
+               cur.idx() = s_start;
+               cur.pit() = 0;
+               cur.pos() = 0;
+               cur.setSelection(false);
                break;
        }
 
@@ -4452,6 +5039,14 @@ void InsetTabular::tabularFeatures(Cursor & cur,
                break;
 
        case Tabular::UNSET_LONGTABULAR:
+               for (row_type i = 0; i < tabular.row_info.size(); ++i) {
+                       if (tabular.ltCaption(i)) {
+                               cur.idx() = tabular.cellIndex(i, 0);
+                               cur.pit() = 0;
+                               cur.pos() = 0;
+                               tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
+                       }
+               }
                tabular.is_long_tabular = false;
                break;
 
@@ -4467,6 +5062,32 @@ void InsetTabular::tabularFeatures(Cursor & cur,
                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::LONGTABULAR_ALIGN_LEFT:
+               tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
+               break;
+
+       case Tabular::LONGTABULAR_ALIGN_CENTER:
+               tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
+               break;
+
+       case Tabular::LONGTABULAR_ALIGN_RIGHT:
+               tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
+               break;
+
+               
+
        case Tabular::SET_ROTATE_CELL:
                for (row_type i = sel_row_start; i <= sel_row_end; ++i)
                        for (col_type j = sel_col_start; j <= sel_col_end; ++j)
@@ -4538,12 +5159,25 @@ void InsetTabular::tabularFeatures(Cursor & cur,
                tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
                break;
 
-       case Tabular::TOGGLE_LTCAPTION:
-               cur.idx() = tabular.setLTCaption(row, !tabular.ltCaption(row));
+       case Tabular::TOGGLE_LTCAPTION: {
+               bool const set = !tabular.ltCaption(row);
+               cur.idx() = tabular.setLTCaption(row, set);
                cur.pit() = 0;
                cur.pos() = 0;
-               cur.selection() = false;
+               cur.setSelection(false);
+
+               if (set) {
+                       // When a row is set as caption, then also insert
+                       // a caption. Otherwise the LaTeX output is broken.
+                       lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
+                       lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
+               } else {
+                       FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
+                       if (lyx::getStatus(fr).enabled())
+                               lyx::dispatch(fr);
+               }
                break;
+       }
 
        case Tabular::SET_BOOKTABS:
                tabular.use_booktabs = true;
@@ -4676,8 +5310,15 @@ bool InsetTabular::pasteClipboard(Cursor & cur)
 {
        if (!paste_tabular)
                return false;
-       col_type const actcol = tabular.cellColumn(cur.idx());
-       row_type const actrow = tabular.cellRow(cur.idx());
+       col_type actcol = tabular.cellColumn(cur.idx());
+       row_type actrow = tabular.cellRow(cur.idx());
+
+       if (cur.selIsMultiCell()) {
+               row_type re;
+               col_type ce;
+               getSelection(cur, actrow, re, actcol, ce);
+       }
+
        for (row_type r1 = 0, r2 = actrow;
             r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
             ++r1, ++r2) {
@@ -4685,7 +5326,7 @@ bool InsetTabular::pasteClipboard(Cursor & cur)
                    c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
                    ++c1, ++c2) {
                        if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
-                           tabular.isPartOfMultiColumn(r2, c2))
+                             tabular.isPartOfMultiColumn(r2, c2))
                                continue;
                        if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
                                --c2;
@@ -4698,8 +5339,11 @@ bool InsetTabular::pasteClipboard(Cursor & cur)
                        shared_ptr<InsetTableCell> inset(
                                new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
                        tabular.setCellInset(r2, c2, inset);
+                       // FIXME?: why do we need to do this explicitly? (EL)
+                       tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
+
                        // FIXME: change tracking (MG)
-                       inset->setChange(Change(cur.buffer().params().trackChanges ?
+                       inset->setChange(Change(buffer().params().trackChanges ?
                                                Change::INSERTED : Change::UNCHANGED));
                        cur.pos() = 0;
                }
@@ -4720,7 +5364,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
@@ -4742,7 +5386,7 @@ bool InsetTabular::isRightToLeft(Cursor & cur) const
        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();
 }
 
@@ -4802,17 +5446,17 @@ void InsetTabular::setChange(Change const & change)
 }
 
 
-void InsetTabular::acceptChanges(BufferParams const & bparams)
+void InsetTabular::acceptChanges()
 {
        for (idx_type idx = 0; idx < nargs(); ++idx)
-               cell(idx)->acceptChanges(bparams);
+               cell(idx)->acceptChanges();
 }
 
 
-void InsetTabular::rejectChanges(BufferParams const & bparams)
+void InsetTabular::rejectChanges()
 {
        for (idx_type idx = 0; idx < nargs(); ++idx)
-               cell(idx)->rejectChanges(bparams);
+               cell(idx)->rejectChanges();
 }
 
 
@@ -4861,7 +5505,7 @@ bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
        col_type ocol = 0;
        row_type row = 0;
        if (usePaste) {
-               paste_tabular.reset(new Tabular(buffer(), rows, maxCols));
+               paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
                loctab = paste_tabular.get();
                cols = 0;
                dirtyTabularStack(true);
@@ -4926,13 +5570,19 @@ bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
 }
 
 
-void InsetTabular::addPreview(PreviewLoader & loader) const
+void InsetTabular::addPreview(DocIterator const & inset_pos,
+       PreviewLoader & loader) const
 {
        row_type const rows = tabular.row_info.size();
        col_type const columns = tabular.column_info.size();
+       DocIterator cell_pos = inset_pos;
+
+       cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
        for (row_type i = 0; i < rows; ++i) {
-               for (col_type j = 0; j < columns; ++j)
-                       tabular.cellInset(i, j)->addPreview(loader);
+               for (col_type j = 0; j < columns; ++j) {
+                       cell_pos.top().idx() = tabular.cellIndex(i, j);
+                       tabular.cellInset(i, j)->addPreview(cell_pos, loader);
+               }
        }
 }