]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
InsetTabular.cpp: multirows inherit the width and the alignment from the column;...
[lyx.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Matthias Ettrich
8  * \author José Matos
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Jürgen Vigna
14  * \author Uwe Stöhr
15  * \author Edwin Leuven
16  *
17  * Full author contact details are available in file CREDITS.
18  */
19
20 #include <config.h>
21
22 #include "InsetTabular.h"
23
24 #include "buffer_funcs.h"
25 #include "Buffer.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "CoordCache.h"
29 #include "Counters.h"
30 #include "Cursor.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "Lexer.h"
38 #include "LyX.h"
39 #include "LyXRC.h"
40 #include "MetricsInfo.h"
41 #include "OutputParams.h"
42 #include "output_xhtml.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
48
49 #include "frontends/Application.h"
50 #include "frontends/alert.h"
51 #include "frontends/Clipboard.h"
52 #include "frontends/Painter.h"
53 #include "frontends/Selection.h"
54
55 #include "support/convert.h"
56 #include "support/debug.h"
57 #include "support/docstream.h"
58 #include "support/FileName.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/lstrings.h"
62
63 #include <boost/scoped_ptr.hpp>
64
65 #include <sstream>
66 #include <iostream>
67 #include <limits>
68 #include <cstring>
69
70 using namespace std;
71 using namespace lyx::support;
72
73
74
75 namespace lyx {
76
77 using cap::dirtyTabularStack;
78 using cap::tabularStackDirty;
79
80 using graphics::PreviewLoader;
81
82 using frontend::Painter;
83 using frontend::Clipboard;
84
85 namespace Alert = frontend::Alert;
86
87
88 namespace {
89
90 int const ADD_TO_HEIGHT = 2; // in cell
91 int const ADD_TO_TABULAR_WIDTH = 6; // horiz space before and after the table
92 int const default_line_space = 10; // ?
93 int const WIDTH_OF_LINE = 5; // space between double lines
94
95
96 ///
97 boost::scoped_ptr<Tabular> paste_tabular;
98
99
100 struct TabularFeature {
101         Tabular::Feature action;
102         string feature;
103         bool need_value;
104 };
105
106
107 TabularFeature tabularFeature[] =
108 {
109         { Tabular::APPEND_ROW, "append-row", false },
110         { Tabular::APPEND_COLUMN, "append-column", false },
111         { Tabular::DELETE_ROW, "delete-row", false },
112         { Tabular::DELETE_COLUMN, "delete-column", false },
113         { Tabular::COPY_ROW, "copy-row", false },
114         { Tabular::COPY_COLUMN, "copy-column", false },
115         { Tabular::SET_LINE_TOP, "set-line-top", true },
116         { Tabular::SET_LINE_BOTTOM, "set-line-bottom", true },
117         { Tabular::SET_LINE_LEFT, "set-line-left", true },
118         { Tabular::SET_LINE_RIGHT, "set-line-right", true },
119         //FIXME: get rid of those 4 TOGGLE actions in favor of the 4 above.
120         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top", false },
121         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom", false },
122         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left", false },
123         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right", false },
124         { Tabular::ALIGN_LEFT, "align-left", false },
125         { Tabular::ALIGN_RIGHT, "align-right", false },
126         { Tabular::ALIGN_CENTER, "align-center", false },
127         { Tabular::ALIGN_BLOCK, "align-block", false },
128         { Tabular::ALIGN_DECIMAL, "align-decimal", false },
129         { Tabular::VALIGN_TOP, "valign-top", false },
130         { Tabular::VALIGN_BOTTOM, "valign-bottom", false },
131         { Tabular::VALIGN_MIDDLE, "valign-middle", false },
132         { Tabular::M_ALIGN_LEFT, "m-align-left", false },
133         { Tabular::M_ALIGN_RIGHT, "m-align-right", false },
134         { Tabular::M_ALIGN_CENTER, "m-align-center", false },
135         { Tabular::M_VALIGN_TOP, "m-valign-top", false },
136         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom", false },
137         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle", false },
138         { Tabular::MULTICOLUMN, "multicolumn", false },
139         { Tabular::SET_MULTICOLUMN, "set-multicolumn", false },
140         { Tabular::UNSET_MULTICOLUMN, "unset-multicolumn", false },
141         { Tabular::MULTIROW, "multirow", false },
142         { Tabular::SET_MULTIROW, "set-multirow", false },
143         { Tabular::UNSET_MULTIROW, "unset-multirow", false },
144         { Tabular::SET_ALL_LINES, "set-all-lines", false },
145         { Tabular::UNSET_ALL_LINES, "unset-all-lines", false },
146         { Tabular::SET_LONGTABULAR, "set-longtabular", false },
147         { Tabular::UNSET_LONGTABULAR, "unset-longtabular", false },
148         { Tabular::SET_PWIDTH, "set-pwidth", true },
149         { Tabular::SET_MPWIDTH, "set-mpwidth", true },
150         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular", false },
151         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular", false },
152         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular", false },
153         { Tabular::SET_ROTATE_CELL, "set-rotate-cell", false },
154         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell", false },
155         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell", false },
156         { Tabular::SET_USEBOX, "set-usebox", true },
157         { Tabular::SET_LTHEAD, "set-lthead", true },
158         { Tabular::UNSET_LTHEAD, "unset-lthead", true },
159         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead", true },
160         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead", true },
161         { Tabular::SET_LTFOOT, "set-ltfoot", true },
162         { Tabular::UNSET_LTFOOT, "unset-ltfoot", true },
163         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot", true },
164         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot", true },
165         { Tabular::SET_LTNEWPAGE, "set-ltnewpage", false },
166         { Tabular::TOGGLE_LTCAPTION, "toggle-ltcaption", false },
167         { Tabular::SET_LTCAPTION, "set-ltcaption", false },
168         { Tabular::UNSET_LTCAPTION, "unset-ltcaption", false },
169         { Tabular::SET_SPECIAL_COLUMN, "set-special-column", true },
170         { Tabular::SET_SPECIAL_MULTICOLUMN, "set-special-multicolumn", true },
171         { Tabular::SET_BOOKTABS, "set-booktabs", false },
172         { Tabular::UNSET_BOOKTABS, "unset-booktabs", false },
173         { Tabular::SET_TOP_SPACE, "set-top-space", true },
174         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space", true },
175         { Tabular::SET_INTERLINE_SPACE, "set-interline-space", true },
176         { Tabular::SET_BORDER_LINES, "set-border-lines", false },
177         { Tabular::TABULAR_VALIGN_TOP, "tabular-valign-top", false},
178         { Tabular::TABULAR_VALIGN_MIDDLE, "tabular-valign-middle", false},
179         { Tabular::TABULAR_VALIGN_BOTTOM, "tabular-valign-bottom", false},
180         { Tabular::LONGTABULAR_ALIGN_LEFT, "longtabular-align-left", false },
181         { Tabular::LONGTABULAR_ALIGN_CENTER, "longtabular-align-center", false },
182         { Tabular::LONGTABULAR_ALIGN_RIGHT, "longtabular-align-right", false },
183         { Tabular::SET_DECIMAL_POINT, "set-decimal-point", true },
184         { Tabular::LAST_ACTION, "", false }
185 };
186
187
188 template <class T>
189 string const write_attribute(string const & name, T const & t)
190 {
191         string const s = tostr(t);
192         return s.empty() ? s : " " + name + "=\"" + s + "\"";
193 }
194
195 template <>
196 string const write_attribute(string const & name, string const & t)
197 {
198         return t.empty() ? t : " " + name + "=\"" + t + "\"";
199 }
200
201
202 template <>
203 string const write_attribute(string const & name, docstring const & t)
204 {
205         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
206 }
207
208
209 template <>
210 string const write_attribute(string const & name, bool const & b)
211 {
212         // we write only true attribute values so we remove a bit of the
213         // file format bloat for tabulars.
214         return b ? write_attribute(name, convert<string>(b)) : string();
215 }
216
217
218 template <>
219 string const write_attribute(string const & name, int const & i)
220 {
221         // we write only true attribute values so we remove a bit of the
222         // file format bloat for tabulars.
223         return i ? write_attribute(name, convert<string>(i)) : string();
224 }
225
226
227 template <>
228 string const write_attribute(string const & name, Tabular::idx_type const & i)
229 {
230         // we write only true attribute values so we remove a bit of the
231         // file format bloat for tabulars.
232         return i ? write_attribute(name, convert<string>(i)) : string();
233 }
234
235
236 template <>
237 string const write_attribute(string const & name, Length const & value)
238 {
239         // we write only the value if we really have one same reson as above.
240         return value.zero() ? string() : write_attribute(name, value.asString());
241 }
242
243
244 string const tostr(LyXAlignment const & num)
245 {
246         switch (num) {
247         case LYX_ALIGN_NONE:
248                 return "none";
249         case LYX_ALIGN_BLOCK:
250                 return "block";
251         case LYX_ALIGN_LEFT:
252                 return "left";
253         case LYX_ALIGN_CENTER:
254                 return "center";
255         case LYX_ALIGN_RIGHT:
256                 return "right";
257         case LYX_ALIGN_LAYOUT:
258                 return "layout";
259         case LYX_ALIGN_SPECIAL:
260                 return "special";
261         case LYX_ALIGN_DECIMAL:
262                 return "decimal";
263         }
264         return string();
265 }
266
267
268 string const tostr(Tabular::HAlignment const & num)
269 {
270         switch (num) {
271         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
272                 return "left";
273         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
274                 return "center";
275         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
276                 return "right";
277         }
278         return string();
279 }
280
281
282 string const tostr(Tabular::VAlignment const & num)
283 {
284         switch (num) {
285         case Tabular::LYX_VALIGN_TOP:
286                 return "top";
287         case Tabular::LYX_VALIGN_MIDDLE:
288                 return "middle";
289         case Tabular::LYX_VALIGN_BOTTOM:
290                 return "bottom";
291         }
292         return string();
293 }
294
295
296 string const tostr(Tabular::BoxType const & num)
297 {
298         switch (num) {
299         case Tabular::BOX_NONE:
300                 return "none";
301         case Tabular::BOX_PARBOX:
302                 return "parbox";
303         case Tabular::BOX_MINIPAGE:
304                 return "minipage";
305         }
306         return string();
307 }
308
309
310 // I would have liked a fromstr template a lot better. (Lgb)
311 bool string2type(string const str, LyXAlignment & num)
312 {
313         if (str == "none")
314                 num = LYX_ALIGN_NONE;
315         else if (str == "block")
316                 num = LYX_ALIGN_BLOCK;
317         else if (str == "left")
318                 num = LYX_ALIGN_LEFT;
319         else if (str == "center")
320                 num = LYX_ALIGN_CENTER;
321         else if (str == "right")
322                 num = LYX_ALIGN_RIGHT;
323         else if (str == "decimal")
324                 num = LYX_ALIGN_DECIMAL;
325         else
326                 return false;
327         return true;
328 }
329
330
331 bool string2type(string const str, Tabular::HAlignment & num)
332 {
333         if (str == "left")
334                 num = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
335         else if (str == "center" )
336                 num = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
337         else if (str == "right")
338                 num = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
339         else
340                 return false;
341         return true;
342 }
343
344
345 bool string2type(string const str, Tabular::VAlignment & num)
346 {
347         if (str == "top")
348                 num = Tabular::LYX_VALIGN_TOP;
349         else if (str == "middle" )
350                 num = Tabular::LYX_VALIGN_MIDDLE;
351         else if (str == "bottom")
352                 num = Tabular::LYX_VALIGN_BOTTOM;
353         else
354                 return false;
355         return true;
356 }
357
358
359 bool string2type(string const str, Tabular::BoxType & num)
360 {
361         if (str == "none")
362                 num = Tabular::BOX_NONE;
363         else if (str == "parbox")
364                 num = Tabular::BOX_PARBOX;
365         else if (str == "minipage")
366                 num = Tabular::BOX_MINIPAGE;
367         else
368                 return false;
369         return true;
370 }
371
372
373 bool string2type(string const str, bool & num)
374 {
375         if (str == "true")
376                 num = true;
377         else if (str == "false")
378                 num = false;
379         else
380                 return false;
381         return true;
382 }
383
384
385 bool getTokenValue(string const & str, char const * token, string & ret)
386 {
387         ret.erase();
388         size_t token_length = strlen(token);
389         size_t pos = str.find(token);
390
391         if (pos == string::npos || pos + token_length + 1 >= str.length()
392                 || str[pos + token_length] != '=')
393                 return false;
394         pos += token_length + 1;
395         char ch = str[pos];
396         if (ch != '"' && ch != '\'') { // only read till next space
397                 ret += ch;
398                 ch = ' ';
399         }
400         while (pos < str.length() - 1 && str[++pos] != ch)
401                 ret += str[pos];
402
403         return true;
404 }
405
406
407 bool getTokenValue(string const & str, char const * token, docstring & ret)
408 {
409         string tmp;
410         bool const success = getTokenValue(str, token, tmp);
411         ret = from_utf8(tmp);
412         return success;
413 }
414
415
416 bool getTokenValue(string const & str, char const * token, int & num)
417 {
418         string tmp;
419         num = 0;
420         if (!getTokenValue(str, token, tmp))
421                 return false;
422         num = convert<int>(tmp);
423         return true;
424 }
425
426
427 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
428 {
429         string tmp;
430         return getTokenValue(str, token, tmp) && string2type(tmp, num);
431 }
432
433
434 bool getTokenValue(string const & str, char const * token,
435                                    Tabular::HAlignment & num)
436 {
437         string tmp;
438         return getTokenValue(str, token, tmp) && string2type(tmp, num);
439 }
440
441
442 bool getTokenValue(string const & str, char const * token,
443                                    Tabular::VAlignment & num)
444 {
445         string tmp;
446         return getTokenValue(str, token, tmp) && string2type(tmp, num);
447 }
448
449
450 bool getTokenValue(string const & str, char const * token,
451                                    Tabular::BoxType & num)
452 {
453         string tmp;
454         return getTokenValue(str, token, tmp) && string2type(tmp, num);
455 }
456
457
458 bool getTokenValue(string const & str, char const * token, bool & flag)
459 {
460         // set the flag always to false as this should be the default for bools
461         // not in the file-format.
462         flag = false;
463         string tmp;
464         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
465 }
466
467
468 bool getTokenValue(string const & str, char const * token, Length & len)
469 {
470         // set the length to be zero() as default as this it should be if not
471         // in the file format.
472         len = Length();
473         string tmp;
474         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
475 }
476
477
478 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
479 {
480         len = Length();
481         flag = false;
482         string tmp;
483         if (!getTokenValue(str, token, tmp))
484                 return false;
485         if (tmp == "default") {
486                 flag = true;
487                 return  true;
488         }
489         return isValidLength(tmp, &len);
490 }
491
492
493 void l_getline(istream & is, string & str)
494 {
495         str.erase();
496         while (str.empty()) {
497                 getline(is, str);
498                 if (!str.empty() && str[str.length() - 1] == '\r')
499                         str.erase(str.length() - 1);
500         }
501 }
502
503 } // namespace
504
505
506 string const featureAsString(Tabular::Feature action)
507 {
508         for (size_t i = 0; i != Tabular::LAST_ACTION; ++i) {
509                 if (tabularFeature[i].action == action)
510                         return tabularFeature[i].feature;
511         }
512         return string();
513 }
514
515
516 InsetTableCell splitCell(InsetTableCell & head, docstring const align_d, bool & hassep)
517 {
518         InsetTableCell tail = InsetTableCell(head);
519         tail.getText(0)->setMacrocontextPosition(
520                 head.getText(0)->macrocontextPosition());
521         tail.setBuffer(head.buffer());
522
523         DocIterator dit = doc_iterator_begin(&head.buffer(), &head);
524         for (; dit; dit.forwardChar())
525                 if (dit.inTexted() && dit.depth()==1
526                         && dit.paragraph().find(align_d, false, false, dit.pos()))
527                         break;
528
529         pit_type const psize = head.paragraphs().front().size();
530         hassep = dit;
531         if (hassep) {
532                 head.paragraphs().front().eraseChars(dit.pos(), psize, false);
533                 tail.paragraphs().front().eraseChars(0, 
534                         dit.pos() < psize ? dit.pos() + 1 : psize, false);
535         }
536
537         return tail;
538 }
539
540
541 /////////////////////////////////////////////////////////////////////
542 //
543 // Tabular
544 //
545 /////////////////////////////////////////////////////////////////////
546
547
548 Tabular::CellData::CellData(Buffer * buf)
549         : cellno(0),
550           width(0),
551           multicolumn(Tabular::CELL_NORMAL),
552           multirow(Tabular::CELL_NORMAL),
553           alignment(LYX_ALIGN_CENTER),
554           valignment(LYX_VALIGN_TOP),
555           decimal_hoffset(0),
556           decimal_width(0),
557           voffset(0),
558           top_line(false),
559           bottom_line(false),
560           left_line(false),
561           right_line(false),
562           usebox(BOX_NONE),
563           rotate(false),
564           inset(new InsetTableCell(buf))
565 {
566         inset->setBuffer(*buf);
567 }
568
569
570 Tabular::CellData::CellData(CellData const & cs)
571         : cellno(cs.cellno),
572           width(cs.width),
573           multicolumn(cs.multicolumn),
574           multirow(cs.multirow),
575           alignment(cs.alignment),
576           valignment(cs.valignment),
577           decimal_hoffset(cs.decimal_hoffset),
578           decimal_width(cs.decimal_width),
579           voffset(cs.voffset),
580           top_line(cs.top_line),
581           bottom_line(cs.bottom_line),
582           left_line(cs.left_line),
583           right_line(cs.right_line),
584           usebox(cs.usebox),
585           rotate(cs.rotate),
586           align_special(cs.align_special),
587           p_width(cs.p_width),
588           inset(static_cast<InsetTableCell *>(cs.inset->clone()))
589 {
590 }
591
592 Tabular::CellData & Tabular::CellData::operator=(CellData cs)
593 {
594         swap(cs);
595         return *this;
596 }
597
598 void Tabular::CellData::swap(CellData & rhs)
599 {
600         std::swap(cellno, rhs.cellno);
601         std::swap(width, rhs.width);
602         std::swap(multicolumn, rhs.multicolumn);
603         std::swap(multirow, rhs.multirow);
604         std::swap(alignment, rhs.alignment);
605         std::swap(valignment, rhs.valignment);
606         std::swap(decimal_hoffset, rhs.decimal_hoffset);
607         std::swap(decimal_width, rhs.decimal_width);
608         std::swap(voffset, rhs.voffset);
609         std::swap(top_line, rhs.top_line);
610         std::swap(bottom_line, rhs.bottom_line);
611         std::swap(left_line, rhs.left_line);
612         std::swap(right_line, rhs.right_line);
613         std::swap(usebox, rhs.usebox);
614         std::swap(rotate, rhs.rotate);
615         std::swap(align_special, rhs.align_special);
616         p_width.swap(rhs.p_width);
617         inset.swap(rhs.inset);
618 }
619
620
621 Tabular::RowData::RowData()
622         : ascent(0),
623           descent(0),
624           top_space_default(false),
625           bottom_space_default(false),
626           interline_space_default(false),
627           endhead(false),
628           endfirsthead(false),
629           endfoot(false),
630           endlastfoot(false),
631           newpage(false),
632           caption(false)
633 {}
634
635
636 Tabular::ColumnData::ColumnData()
637         : alignment(LYX_ALIGN_CENTER),
638           valignment(LYX_VALIGN_TOP),
639           width(0)
640 {
641 }
642
643
644 Tabular::ltType::ltType()
645         : topDL(false),
646           bottomDL(false),
647           empty(false)
648 {}
649
650
651 Tabular::Tabular(Buffer * buffer, row_type rows_arg, col_type columns_arg)
652 {
653         init(buffer, rows_arg, columns_arg);
654 }
655
656
657 void Tabular::setBuffer(Buffer & buffer)
658 {
659         buffer_ = &buffer;
660         for (row_type i = 0; i < nrows(); ++i)
661                 for (col_type j = 0; j < ncols(); ++j)
662                         cell_info[i][j].inset->setBuffer(*buffer_);
663 }
664
665
666 // activates all lines and sets all widths to 0
667 void Tabular::init(Buffer * buf, row_type rows_arg,
668                       col_type columns_arg)
669 {
670         buffer_ = buf;
671         row_info = row_vector(rows_arg);
672         column_info = column_vector(columns_arg);
673         cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf)));
674         row_info.reserve(10);
675         column_info.reserve(10);
676         cell_info.reserve(100);
677         updateIndexes();
678         is_long_tabular = false;
679         tabular_valignment = LYX_VALIGN_MIDDLE;
680         longtabular_alignment = LYX_LONGTABULAR_ALIGN_CENTER;
681         rotate = false;
682         use_booktabs = false;
683         // set silly default lines
684         for (row_type r = 0; r < nrows(); ++r)
685                 for (col_type c = 0; c < ncols(); ++c) {
686                         cell_info[r][c].inset->setBuffer(*buffer_);
687                         cell_info[r][c].top_line = true;
688                         cell_info[r][c].left_line = true;
689                         cell_info[r][c].bottom_line = r == 0 || r == nrows() - 1;
690                         cell_info[r][c].right_line = c == ncols() - 1;
691                 }
692 }
693
694
695 void Tabular::appendRow(idx_type const cell)
696 {
697         row_type const row = cellRow(cell);
698
699         row_info.insert(row_info.begin() + row + 1, RowData());
700         row_info[row + 1] = row_info[row];
701
702         cell_info.insert(cell_info.begin() + row + 1,
703                 cell_vector(ncols(), CellData(buffer_)));
704         for (col_type c = 0; c < ncols(); ++c) {
705                 if (cell_info[row][c].multirow == CELL_BEGIN_OF_MULTIROW)
706                         cell_info[row + 1][c].multirow = CELL_PART_OF_MULTIROW;
707                 else
708                         cell_info[row + 1][c].multirow = cell_info[row][c].multirow;
709         }
710         updateIndexes();
711
712         for (col_type c = 0; c < ncols(); ++c) {
713                 if (isPartOfMultiRow(row, c))
714                         continue;
715                 // inherit line settings
716                 idx_type const i = cellIndex(row + 1, c);
717                 idx_type const j = cellIndex(row, c);
718                 setLeftLine(i, leftLine(j));
719                 setRightLine(i, rightLine(j));
720                 setTopLine(i, topLine(j));
721                 if (topLine(j) && bottomLine(j)) {
722                         setBottomLine(i, true);
723                         setBottomLine(j, false);
724                 }
725                 // mark track changes
726                 if (buffer().params().trackChanges)
727                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
728         }
729 }
730
731
732 void Tabular::deleteRow(row_type const row)
733 {
734         // Not allowed to delete last row
735         if (nrows() == 1)
736                 return;
737
738         for (col_type c = 0; c < ncols(); ++c) {
739                 // Care about multirow cells
740                 if (row + 1 < nrows() &&
741                     cell_info[row][c].multirow == CELL_BEGIN_OF_MULTIROW &&
742                     cell_info[row + 1][c].multirow == CELL_PART_OF_MULTIROW) {
743                                 cell_info[row + 1][c].multirow = CELL_BEGIN_OF_MULTIROW;
744                 }
745         }
746         row_info.erase(row_info.begin() + row);
747         cell_info.erase(cell_info.begin() + row);
748         updateIndexes();
749 }
750
751
752 void Tabular::copyRow(row_type const row)
753 {
754         row_info.insert(row_info.begin() + row, row_info[row]);
755         cell_info.insert(cell_info.begin() + row, cell_info[row]);
756
757         if (buffer().params().trackChanges)
758                 for (col_type c = 0; c < ncols(); ++c)
759                         cell_info[row + 1][c].inset->setChange(Change(Change::INSERTED));
760
761         updateIndexes();
762 }
763
764
765 void Tabular::appendColumn(idx_type const cell)
766 {
767         col_type const c = cellColumn(cell);
768         
769         column_info.insert(column_info.begin() + c + 1, ColumnData());
770         column_info[c + 1] = column_info[c];
771
772         for (row_type r = 0; r < nrows(); ++r) {
773                 cell_info[r].insert(cell_info[r].begin() + c + 1, 
774                         CellData(buffer_));
775                 if (cell_info[r][c].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
776                         cell_info[r][c + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
777                 else
778                         cell_info[r][c + 1].multicolumn = cell_info[r][c].multicolumn;
779         }
780         updateIndexes();
781         for (row_type r = 0; r < nrows(); ++r) {
782                 // inherit line settings
783                 idx_type const i = cellIndex(r, c + 1);
784                 idx_type const j = cellIndex(r, c);
785                 setBottomLine(i, bottomLine(j));
786                 setTopLine(i, topLine(j));
787                 setLeftLine(i, leftLine(j));
788                 if (rightLine(j) && rightLine(j)) {
789                         setRightLine(i, true);
790                         setRightLine(j, false);
791                 }
792                 if (buffer().params().trackChanges)
793                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
794         }
795 }
796
797
798 void Tabular::deleteColumn(col_type const col)
799 {
800         // Not allowed to delete last column
801         if (ncols() == 1)
802                 return;
803
804         for (row_type r = 0; r < nrows(); ++r) {
805                 // Care about multicolumn cells
806                 if (col + 1 < ncols() &&
807                     cell_info[r][col].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
808                     cell_info[r][col + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
809                                 cell_info[r][col + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
810                 }
811                 cell_info[r].erase(cell_info[r].begin() + col);
812         }
813         column_info.erase(column_info.begin() + col);
814         updateIndexes();
815 }
816
817
818 void Tabular::copyColumn(col_type const col)
819 {
820         BufferParams const & bp = buffer().params();
821         column_info.insert(column_info.begin() + col, column_info[col]);
822
823         for (row_type r = 0; r < nrows(); ++r) {
824                 cell_info[r].insert(cell_info[r].begin() + col, cell_info[r][col]);
825                 if (bp.trackChanges)
826                         cell_info[r][col + 1].inset->setChange(Change(Change::INSERTED));
827         }
828         updateIndexes();
829 }
830
831
832 void Tabular::updateIndexes()
833 {
834         setBuffer(buffer());
835         numberofcells = 0;
836         for (row_type row = 0; row < nrows(); ++row)
837                 for (col_type column = 0; column < ncols(); ++column) {
838                         if (!isPartOfMultiColumn(row, column)
839                                 && !isPartOfMultiRow(row, column))
840                                 ++numberofcells;
841                         if (isPartOfMultiRow(row, column))
842                                 cell_info[row][column].cellno = cell_info[row - 1][column].cellno;
843                         else
844                                 cell_info[row][column].cellno = numberofcells - 1;
845                 }
846
847         rowofcell.resize(numberofcells);
848         columnofcell.resize(numberofcells);
849         idx_type i = 0;
850         for (row_type row = 0; row < nrows(); ++row)
851                 for (col_type column = 0; column < ncols(); ++column) {
852                         if (isPartOfMultiColumn(row, column))
853                                 continue;
854                         setFixedWidth(row, column);
855                         cell_info[row][column].inset->setContentAlignment(
856                                 getAlignment(cellIndex(row, column)));
857                         if (!isPartOfMultiRow(row, column)) {
858                                 columnofcell[i] = column;
859                                 rowofcell[i] = row;
860                         } else
861                                 continue;
862                         ++i;
863                 }
864 }
865
866
867 Tabular::idx_type Tabular::numberOfCellsInRow(row_type const row) const
868 {
869         idx_type result = 0;
870         for (col_type c = 0; c < ncols(); ++c)
871                 if (cell_info[row][c].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
872                         ++result;
873         return result;
874 }
875
876
877 bool Tabular::topLine(idx_type const cell) const
878 {
879         return cellInfo(cell).top_line;
880 }
881
882
883 bool Tabular::bottomLine(idx_type const cell) const
884 {
885         return cellInfo(cell).bottom_line;
886 }
887
888
889 bool Tabular::leftLine(idx_type cell) const
890 {
891         if (use_booktabs)
892                 return false;
893         return cellInfo(cell).left_line;
894 }
895
896
897 bool Tabular::rightLine(idx_type cell) const
898 {
899         if (use_booktabs)
900                 return false;
901         return cellInfo(cell).right_line;
902 }
903
904
905 int Tabular::interRowSpace(row_type row) const
906 {
907         if (!row || row >= nrows())
908                 return 0;
909
910         int const interline_space = row_info[row - 1].interline_space_default ?
911                 default_line_space :
912                 row_info[row - 1].interline_space.inPixels(width());
913         if (rowTopLine(row) && rowBottomLine(row - 1))
914                 return interline_space + WIDTH_OF_LINE;
915         return interline_space;
916 }
917
918
919 int Tabular::interColumnSpace(idx_type cell) const
920 {
921         col_type const nextcol = cellColumn(cell) + columnSpan(cell);
922         if (rightLine(cell) && nextcol < ncols()
923                 && leftLine(cellIndex(cellRow(cell), nextcol)))
924                 return WIDTH_OF_LINE;
925         return 0;
926 }
927
928
929 int Tabular::cellWidth(idx_type cell) const
930 {
931         int w = 0;
932         col_type const span = columnSpan(cell);
933         col_type const col = cellColumn(cell);
934         for(col_type c = col; c < col + span ; ++c)
935                 w += column_info[c].width;
936         return w;
937 }
938
939
940 int Tabular::cellHeight(idx_type cell) const
941 {
942         row_type const span = rowSpan(cell);
943         row_type const row = cellRow(cell);
944         int h = 0;
945         for(row_type r = row; r < row + span ; ++r) {
946                 h += rowAscent(r) + rowDescent(r);
947                 if (r != row + span - 1)
948                         h += interRowSpace(r + 1);
949         }
950
951         return h;
952 }
953
954
955 bool Tabular::updateColumnWidths()
956 {
957         vector<int> max_dwidth(ncols(), 0);
958         for(col_type c = 0; c < ncols(); ++c)
959                 for(row_type r = 0; r < nrows(); ++r) {
960                         idx_type const i = cellIndex(r, c);
961                         if (getAlignment(i) == LYX_ALIGN_DECIMAL)
962                                 max_dwidth[c] = max(max_dwidth[c], cell_info[r][c].decimal_width);
963                 }
964
965         bool update = false;
966         // for each col get max of single col cells
967         for(col_type c = 0; c < ncols(); ++c) {
968                 int new_width = 0;
969                 for(row_type r = 0; r < nrows(); ++r) {
970                         idx_type const i = cellIndex(r, c);
971                         if (columnSpan(i) == 1) {
972                                 if (getAlignment(i) == LYX_ALIGN_DECIMAL
973                                         && cell_info[r][c].decimal_width!=0)
974                                         new_width = max(new_width, cellInfo(i).width 
975                                                 + max_dwidth[c] - cellInfo(i).decimal_width);
976                                 else
977                                         new_width = max(new_width, cellInfo(i).width);
978                         }
979                 }
980
981                 if (column_info[c].width != new_width) {
982                         column_info[c].width = new_width;
983                         update = true;
984                 }
985         }
986         // update col widths to fit merged cells
987         for(col_type c = 0; c < ncols(); ++c)
988                 for(row_type r = 0; r < nrows(); ++r) {
989                         idx_type const i = cellIndex(r, c);
990                         int const span = columnSpan(i);
991                         if (span == 1 || c > cellColumn(i))
992                                 continue;
993
994                         int old_width = 0;
995                         for(col_type j = c; j < c + span ; ++j)
996                                 old_width += column_info[j].width;
997
998                         if (cellInfo(i).width > old_width) {
999                                 column_info[c + span - 1].width += cellInfo(i).width - old_width;
1000                                 update = true;
1001                         }
1002                 }
1003
1004         return update;
1005 }
1006
1007
1008 int Tabular::width() const
1009 {
1010         int width = 0;
1011         for (col_type c = 0; c < ncols(); ++c)
1012                 width += column_info[c].width;
1013         return width;
1014 }
1015
1016
1017 void Tabular::setAlignment(idx_type cell, LyXAlignment align,
1018                               bool onlycolumn)
1019 {
1020         col_type const col = cellColumn(cell);
1021         if (onlycolumn || !isMultiColumn(cell)) {
1022                 column_info[col].alignment = align;
1023                 docstring & dpoint = column_info[col].decimal_point;
1024                 if (align == LYX_ALIGN_DECIMAL && dpoint.empty())
1025                         dpoint = from_utf8(lyxrc.default_decimal_point);
1026         } else {
1027                 cellInfo(cell).alignment = align;
1028                 cellInset(cell).get()->setContentAlignment(align);
1029         }
1030 }
1031
1032
1033 void Tabular::setVAlignment(idx_type cell, VAlignment align,
1034                                bool onlycolumn)
1035 {
1036         if (!isMultiColumn(cell) || onlycolumn)
1037                 column_info[cellColumn(cell)].valignment = align;
1038         if (!onlycolumn)
1039                 cellInfo(cell).valignment = align;
1040 }
1041
1042
1043 namespace {
1044
1045 /**
1046  * Allow line and paragraph breaks for fixed width cells or disallow them,
1047  * merge cell paragraphs and reset layout to standard for variable width
1048  * cells.
1049  */
1050 void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
1051 {
1052         inset->setAutoBreakRows(fixedWidth);
1053         inset->toggleFixedWidth(fixedWidth);
1054         if (fixedWidth)
1055                 return;
1056
1057         // merge all paragraphs to one
1058         BufferParams const & bp = cur.bv().buffer().params();
1059         while (inset->paragraphs().size() > 1)
1060                 mergeParagraph(bp, inset->paragraphs(), 0);
1061
1062         // reset layout
1063         cur.push(*inset);
1064         // undo information has already been recorded
1065         inset->getText(0)->setLayout(0, cur.lastpit() + 1,
1066                         bp.documentClass().plainLayoutName());
1067         cur.pop();
1068 }
1069
1070 }
1071
1072
1073 void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
1074                 Length const & width)
1075 {
1076         col_type const c = cellColumn(cell);
1077
1078         column_info[c].p_width = width;
1079         // reset the vertical alignment to top if the fixed with
1080         // is removed or zero because only fixed width columns can
1081         // have a vertical alignment
1082         if (column_info[c].p_width.zero())
1083                 column_info[c].valignment = LYX_VALIGN_TOP;
1084         for (row_type r = 0; r < nrows(); ++r) {
1085                 idx_type const cell = cellIndex(r, c);
1086                 // because of multicolumns
1087                 toggleFixedWidth(cur, cellInset(cell).get(),
1088                                  !getPWidth(cell).zero());
1089         }
1090         // cur paragraph can become invalid after paragraphs were merged
1091         if (cur.pit() > cur.lastpit())
1092                 cur.pit() = cur.lastpit();
1093         // cur position can become invalid after newlines were removed
1094         if (cur.pos() > cur.lastpos())
1095                 cur.pos() = cur.lastpos();
1096 }
1097
1098
1099 bool Tabular::setFixedWidth(row_type r, col_type c)
1100 {
1101         bool const multicol = cell_info[r][c].multicolumn != CELL_NORMAL;
1102         bool const fixed_width = (!column_info[c].p_width.zero() && !multicol)
1103               || (multicol && !cell_info[r][c].p_width.zero());
1104         cell_info[r][c].inset->toggleFixedWidth(fixed_width);
1105         return fixed_width;
1106 }
1107
1108
1109 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
1110                 Length const & width)
1111 {
1112         if (!isMultiColumn(cell))
1113                 return false;
1114
1115         cellInfo(cell).p_width = width;
1116         toggleFixedWidth(cur, cellInset(cell).get(), !width.zero());
1117         // cur paragraph can become invalid after paragraphs were merged
1118         if (cur.pit() > cur.lastpit())
1119                 cur.pit() = cur.lastpit();
1120         // cur position can become invalid after newlines were removed
1121         if (cur.pos() > cur.lastpos())
1122                 cur.pos() = cur.lastpos();
1123         return true;
1124 }
1125
1126
1127 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
1128                                  Tabular::Feature what)
1129 {
1130         if (what == SET_SPECIAL_MULTICOLUMN)
1131                 cellInfo(cell).align_special = special;
1132         else
1133                 column_info[cellColumn(cell)].align_special = special;
1134 }
1135
1136
1137 void Tabular::setTopLine(idx_type i, bool line)
1138 {
1139         cellInfo(i).top_line = line;
1140 }
1141
1142
1143 void Tabular::setBottomLine(idx_type i, bool line)
1144 {
1145         cellInfo(i).bottom_line = line;
1146 }
1147
1148
1149 void Tabular::setLeftLine(idx_type cell, bool line)
1150 {
1151         cellInfo(cell).left_line = line;
1152 }
1153
1154
1155 void Tabular::setRightLine(idx_type cell, bool line)
1156 {
1157         cellInfo(cell).right_line = line;
1158 }
1159
1160 bool Tabular::rowTopLine(row_type r) const
1161 {
1162         bool all_rows_set = true;
1163         for (col_type c = 0; all_rows_set && c < ncols(); ++c)
1164                 all_rows_set = cellInfo(cellIndex(r, c)).top_line;
1165         return all_rows_set;
1166 }
1167
1168
1169 bool Tabular::rowBottomLine(row_type r) const
1170 {
1171         bool all_rows_set = true;
1172         for (col_type c = 0; all_rows_set && c < ncols(); ++c)
1173                 all_rows_set = cellInfo(cellIndex(r, c)).bottom_line;
1174         return all_rows_set;
1175 }
1176
1177
1178 bool Tabular::columnLeftLine(col_type c) const
1179 {
1180         if (use_booktabs)
1181                 return false;
1182
1183         int nrows_left = 0;
1184         int total = 0;
1185         for (row_type r = 0; r < nrows(); ++r) {
1186                 idx_type const i = cellIndex(r, c);
1187                 if (c == cellColumn(i)) {
1188                         ++total;
1189                         bool right = c > 0 && cellInfo(cellIndex(r, c - 1)).right_line;
1190                         if (cellInfo(i).left_line || right)
1191                                 ++nrows_left;
1192                 }
1193         }
1194         return 2 * nrows_left >= total;
1195 }
1196
1197
1198 bool Tabular::columnRightLine(col_type c) const
1199 {
1200         if (use_booktabs)
1201                 return false;
1202
1203         int nrows_right = 0;
1204         int total = 0;
1205         for (row_type r = 0; r < nrows(); ++r) {
1206                 idx_type i = cellIndex(r, c);
1207                 if (c == cellColumn(i) + columnSpan(i) - 1) {
1208                         ++total;
1209                         bool left = (c + 1 < ncols() 
1210                                 && cellInfo(cellIndex(r, c + 1)).left_line)
1211                                 || c + 1 == ncols();
1212                         if (cellInfo(i).right_line && left)
1213                                 ++nrows_right;
1214                 }
1215         }
1216         return 2 * nrows_right >= total;
1217 }
1218
1219
1220 LyXAlignment Tabular::getAlignment(idx_type cell, bool onlycolumn) const
1221 {
1222         if (!onlycolumn && (isMultiColumn(cell) || isMultiRow(cell)))
1223                 return cellInfo(cell).alignment;
1224         
1225         return column_info[cellColumn(cell)].alignment;
1226 }
1227
1228
1229 Tabular::VAlignment
1230 Tabular::getVAlignment(idx_type cell, bool onlycolumn) const
1231 {
1232         if (!onlycolumn && (isMultiColumn(cell) || isMultiRow(cell)))
1233                 return cellInfo(cell).valignment;
1234         return column_info[cellColumn(cell)].valignment;
1235 }
1236
1237
1238 Length const Tabular::getPWidth(idx_type cell) const
1239 {
1240         if (isMultiColumn(cell))
1241                 return cellInfo(cell).p_width;
1242         return column_info[cellColumn(cell)].p_width;
1243 }
1244
1245
1246 int Tabular::textHOffset(idx_type cell) const
1247 {
1248         // the LaTeX Way :-(
1249         int x = WIDTH_OF_LINE;
1250
1251         int const w = cellWidth(cell) - cellInfo(cell).width;
1252
1253         switch (getAlignment(cell)) {
1254         case LYX_ALIGN_CENTER:
1255                 x += w / 2;
1256                 break;
1257         case LYX_ALIGN_RIGHT:
1258                 x += w;
1259                 break;
1260         case LYX_ALIGN_DECIMAL: {
1261                 // we center when no decimal point
1262                 if (cellInfo(cell).decimal_width == 0) {
1263                         x += w / 2;
1264                         break;
1265                 }
1266                 col_type const c = cellColumn(cell);
1267                 int max_dhoffset = 0;
1268                 for(row_type r = 0; r < row_info.size() ; ++r) {
1269                         idx_type const i = cellIndex(r, c);
1270                         if (getAlignment(i) == LYX_ALIGN_DECIMAL
1271                                 && cellInfo(i).decimal_width != 0)
1272                                 max_dhoffset = max(max_dhoffset, cellInfo(i).decimal_hoffset);
1273                 }
1274                 x += max_dhoffset - cellInfo(cell).decimal_hoffset;
1275         }
1276         default:
1277                 // LYX_ALIGN_LEFT: nothing :-)
1278                 break;
1279         }
1280
1281         return x;
1282 }
1283
1284
1285 int Tabular::textVOffset(idx_type cell) const
1286 {
1287         int voffset = cellInfo(cell).voffset;
1288         if (isMultiRow(cell)) {
1289                 row_type const row = cellRow(cell);
1290                 voffset += (cellHeight(cell) - rowAscent(row) - rowDescent(row))/2; 
1291         }
1292         return voffset;
1293 }
1294
1295
1296 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
1297 {
1298         col_type c = 0;
1299         while (cell_info[row][c].multirow == CELL_PART_OF_MULTIROW)
1300                 ++c;
1301         return cell_info[row][c].cellno;
1302 }
1303
1304
1305 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
1306 {
1307         col_type c = ncols() - 1;
1308         while (cell_info[row][c].multirow == CELL_PART_OF_MULTIROW
1309                 || cell_info[row][c].multicolumn == CELL_PART_OF_MULTICOLUMN)
1310                 --c;
1311         return cell_info[row][c].cellno;
1312 }
1313
1314
1315 Tabular::row_type Tabular::cellRow(idx_type cell) const
1316 {
1317         if (cell >= numberofcells)
1318                 return nrows() - 1;
1319         if (cell == npos)
1320                 return 0;
1321         return rowofcell[cell];
1322 }
1323
1324
1325 Tabular::col_type Tabular::cellColumn(idx_type cell) const
1326 {
1327         if (cell >= numberofcells)
1328                 return ncols() - 1;
1329         if (cell == npos)
1330                 return 0;       
1331         return columnofcell[cell];
1332 }
1333
1334
1335 void Tabular::write(ostream & os) const
1336 {
1337         // header line
1338         os << "<lyxtabular"
1339            << write_attribute("version", 3)
1340            << write_attribute("rows", nrows())
1341            << write_attribute("columns", ncols())
1342            << ">\n";
1343         // global longtable options
1344         os << "<features"
1345            << write_attribute("rotate", rotate)
1346            << write_attribute("booktabs", use_booktabs)
1347            << write_attribute("islongtable", is_long_tabular)
1348            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1349            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1350            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1351            << write_attribute("headTopDL", endhead.topDL)
1352            << write_attribute("headBottomDL", endhead.bottomDL)
1353            << write_attribute("footTopDL", endfoot.topDL)
1354            << write_attribute("footBottomDL", endfoot.bottomDL)
1355            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1356            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1357            << write_attribute("lastFootEmpty", endlastfoot.empty);
1358         // longtables cannot be aligned vertically
1359         if (!is_long_tabular)
1360            os << write_attribute("tabularvalignment", tabular_valignment);
1361         if (is_long_tabular)
1362            os << write_attribute("longtabularalignment",
1363                                  longtabular_alignment);
1364         os << ">\n";
1365         for (col_type c = 0; c < ncols(); ++c) {
1366                 os << "<column"
1367                    << write_attribute("alignment", column_info[c].alignment);
1368                 if (column_info[c].alignment == LYX_ALIGN_DECIMAL)
1369                    os << write_attribute("decimal_point", column_info[c].decimal_point);
1370                 os << write_attribute("valignment", column_info[c].valignment)
1371                    << write_attribute("width", column_info[c].p_width.asString())
1372                    << write_attribute("special", column_info[c].align_special)
1373                    << ">\n";
1374         }
1375         for (row_type r = 0; r < nrows(); ++r) {
1376                 static const string def("default");
1377                 os << "<row";
1378                 if (row_info[r].top_space_default)
1379                         os << write_attribute("topspace", def);
1380                 else
1381                         os << write_attribute("topspace", row_info[r].top_space);
1382                 if (row_info[r].bottom_space_default)
1383                         os << write_attribute("bottomspace", def);
1384                 else
1385                         os << write_attribute("bottomspace", row_info[r].bottom_space);
1386                 if (row_info[r].interline_space_default)
1387                         os << write_attribute("interlinespace", def);
1388                 else
1389                         os << write_attribute("interlinespace", row_info[r].interline_space);
1390                 os << write_attribute("endhead", row_info[r].endhead)
1391                    << write_attribute("endfirsthead", row_info[r].endfirsthead)
1392                    << write_attribute("endfoot", row_info[r].endfoot)
1393                    << write_attribute("endlastfoot", row_info[r].endlastfoot)
1394                    << write_attribute("newpage", row_info[r].newpage)
1395                    << write_attribute("caption", row_info[r].caption)
1396                    << ">\n";
1397                 for (col_type c = 0; c < ncols(); ++c) {
1398                         os << "<cell"
1399                            << write_attribute("multicolumn", cell_info[r][c].multicolumn)
1400                            << write_attribute("multirow", cell_info[r][c].multirow)
1401                            << write_attribute("alignment", cell_info[r][c].alignment)
1402                            << write_attribute("valignment", cell_info[r][c].valignment)
1403                            << write_attribute("topline", cell_info[r][c].top_line)
1404                            << write_attribute("bottomline", cell_info[r][c].bottom_line)
1405                            << write_attribute("leftline", cell_info[r][c].left_line)
1406                            << write_attribute("rightline", cell_info[r][c].right_line)
1407                            << write_attribute("rotate", cell_info[r][c].rotate)
1408                            << write_attribute("usebox", cell_info[r][c].usebox)
1409                            << write_attribute("width", cell_info[r][c].p_width)
1410                            << write_attribute("special", cell_info[r][c].align_special)
1411                            << ">\n";
1412                         os << "\\begin_inset ";
1413                         cell_info[r][c].inset->write(os);
1414                         os << "\n\\end_inset\n"
1415                            << "</cell>\n";
1416                 }
1417                 os << "</row>\n";
1418         }
1419         os << "</lyxtabular>\n";
1420 }
1421
1422
1423 void Tabular::read(Lexer & lex)
1424 {
1425         string line;
1426         istream & is = lex.getStream();
1427
1428         l_getline(is, line);
1429         if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
1430                 LASSERT(false, /**/);
1431                 return;
1432         }
1433
1434         int version;
1435         if (!getTokenValue(line, "version", version))
1436                 return;
1437         LASSERT(version >= 2, /**/);
1438
1439         int rows_arg;
1440         if (!getTokenValue(line, "rows", rows_arg))
1441                 return;
1442         int columns_arg;
1443         if (!getTokenValue(line, "columns", columns_arg))
1444                 return;
1445         init(buffer_, rows_arg, columns_arg);
1446         l_getline(is, line);
1447         if (!prefixIs(line, "<features")) {
1448                 lyxerr << "Wrong tabular format (expected <features ...> got"
1449                        << line << ')' << endl;
1450                 return;
1451         }
1452         getTokenValue(line, "rotate", rotate);
1453         getTokenValue(line, "booktabs", use_booktabs);
1454         getTokenValue(line, "islongtable", is_long_tabular);
1455         getTokenValue(line, "tabularvalignment", tabular_valignment);
1456         getTokenValue(line, "longtabularalignment", longtabular_alignment);
1457         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1458         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1459         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1460         getTokenValue(line, "headTopDL", endhead.topDL);
1461         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1462         getTokenValue(line, "footTopDL", endfoot.topDL);
1463         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1464         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1465         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1466         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1467
1468         for (col_type c = 0; c < ncols(); ++c) {
1469                 l_getline(is,line);
1470                 if (!prefixIs(line,"<column")) {
1471                         lyxerr << "Wrong tabular format (expected <column ...> got"
1472                                << line << ')' << endl;
1473                         return;
1474                 }
1475                 getTokenValue(line, "alignment", column_info[c].alignment);
1476                 getTokenValue(line, "decimal_point", column_info[c].decimal_point);
1477                 getTokenValue(line, "valignment", column_info[c].valignment);
1478                 getTokenValue(line, "width", column_info[c].p_width);
1479                 getTokenValue(line, "special", column_info[c].align_special);
1480         }
1481
1482         for (row_type i = 0; i < nrows(); ++i) {
1483                 l_getline(is, line);
1484                 if (!prefixIs(line, "<row")) {
1485                         lyxerr << "Wrong tabular format (expected <row ...> got"
1486                                << line << ')' << endl;
1487                         return;
1488                 }
1489                 getTokenValue(line, "topspace", row_info[i].top_space,
1490                               row_info[i].top_space_default);
1491                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1492                               row_info[i].bottom_space_default);
1493                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1494                               row_info[i].interline_space_default);
1495                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1496                 getTokenValue(line, "endhead", row_info[i].endhead);
1497                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1498                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1499                 getTokenValue(line, "newpage", row_info[i].newpage);
1500                 getTokenValue(line, "caption", row_info[i].caption);
1501                 for (col_type j = 0; j < ncols(); ++j) {
1502                         l_getline(is, line);
1503                         if (!prefixIs(line, "<cell")) {
1504                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1505                                        << line << ')' << endl;
1506                                 return;
1507                         }
1508                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1509                         getTokenValue(line, "multirow", cell_info[i][j].multirow);
1510                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1511                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1512                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1513                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1514                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1515                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1516                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1517                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1518                         getTokenValue(line, "width", cell_info[i][j].p_width);
1519                         setFixedWidth(i,j);
1520                         getTokenValue(line, "special", cell_info[i][j].align_special);
1521                         l_getline(is, line);
1522                         if (prefixIs(line, "\\begin_inset")) {
1523                                 cell_info[i][j].inset->setBuffer(*buffer_);
1524                                 cell_info[i][j].inset->read(lex);
1525                                 l_getline(is, line);
1526                         }
1527                         if (!prefixIs(line, "</cell>")) {
1528                                 lyxerr << "Wrong tabular format (expected </cell> got"
1529                                        << line << ')' << endl;
1530                                 return;
1531                         }
1532                 }
1533                 l_getline(is, line);
1534                 if (!prefixIs(line, "</row>")) {
1535                         lyxerr << "Wrong tabular format (expected </row> got"
1536                                << line << ')' << endl;
1537                         return;
1538                 }
1539         }
1540         while (!prefixIs(line, "</lyxtabular>")) {
1541                 l_getline(is, line);
1542         }
1543         updateIndexes();
1544 }
1545
1546
1547 bool Tabular::isMultiColumn(idx_type cell) const
1548 {
1549         return (cellInfo(cell).multicolumn == CELL_BEGIN_OF_MULTICOLUMN 
1550                 || cellInfo(cell).multicolumn == CELL_PART_OF_MULTICOLUMN);
1551 }
1552
1553
1554 Tabular::CellData & Tabular::cellInfo(idx_type cell) const
1555 {
1556         return cell_info[cellRow(cell)][cellColumn(cell)];
1557 }
1558
1559
1560 Tabular::idx_type Tabular::setMultiColumn(idx_type cell, idx_type number)
1561 {
1562         idx_type const col = cellColumn(cell);
1563         idx_type const row = cellRow(cell);
1564         for (idx_type i = 0; i < number; ++i)
1565                 unsetMultiRow(cellIndex(row, col + i));
1566
1567         // unsetting of multirow may have invalidated cell index
1568         cell = cellIndex(row, col);
1569         CellData & cs = cellInfo(cell);
1570         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1571         if (column_info[col].alignment != LYX_ALIGN_DECIMAL)
1572                 cs.alignment = column_info[col].alignment;
1573         if (col > 0)
1574                 setRightLine(cell, rightLine(cellIndex(row, col - 1)));
1575
1576         for (idx_type i = 1; i < number; ++i) {
1577                 CellData & cs1 = cellInfo(cell + i);
1578                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1579                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1580                 cs1.inset->clear();
1581         }
1582         updateIndexes();
1583         return cell;
1584 }
1585
1586
1587 bool Tabular::isMultiRow(idx_type cell) const
1588 {
1589         return (cellInfo(cell).multirow == CELL_BEGIN_OF_MULTIROW
1590                 || cellInfo(cell).multirow == CELL_PART_OF_MULTIROW);
1591 }
1592
1593
1594 Tabular::idx_type Tabular::setMultiRow(idx_type cell, idx_type number)
1595 {
1596         idx_type const col = cellColumn(cell);
1597         idx_type const row = cellRow(cell);
1598         for (idx_type i = 0; i < number; ++i)
1599                 unsetMultiColumn(cellIndex(row + i, col));
1600
1601         // unsetting of multicol may have invalidated cell index
1602         cell = cellIndex(row, col);
1603         CellData & cs = cellInfo(cell);
1604         cs.multirow = CELL_BEGIN_OF_MULTIROW;
1605         cs.valignment = LYX_VALIGN_MIDDLE;
1606         // FIXME: the horizontal alignment of multirow cells can only
1607         // be changed for the whole table,
1608         // support for this needs to be implemented but us a fileformat
1609         // change (assigning this to uwestoehr)
1610         // until LyX supports this, use the deault alignment of multirow
1611         // cells: left
1612         cs.alignment = LYX_ALIGN_CENTER; 
1613
1614         // set the bottom row of the last selected cell
1615         setBottomLine(cell, bottomLine(cell + (number - 1)*ncols()));
1616
1617         for (idx_type i = 1; i < number; ++i) {
1618                 CellData & cs1 = cell_info[row + i][col];
1619                 cs1.multirow = CELL_PART_OF_MULTIROW;
1620                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1621                 cs1.inset->clear();
1622         }
1623         updateIndexes();
1624         return cell;
1625 }
1626
1627
1628 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
1629 {
1630         row_type const row = cellRow(cell);
1631         col_type const col = cellColumn(cell);
1632         int span = 1;
1633         while (col + span < ncols() && isPartOfMultiColumn(row, col + span))
1634                 ++span;
1635
1636         return span;
1637 }
1638
1639
1640 Tabular::idx_type Tabular::rowSpan(idx_type cell) const
1641 {
1642         col_type const column = cellColumn(cell);
1643         col_type row = cellRow(cell) + 1;
1644         while (row < nrows() && isPartOfMultiRow(row, column))
1645                 ++row;
1646         
1647         return row - cellRow(cell);
1648 }
1649
1650
1651 void Tabular::unsetMultiColumn(idx_type cell)
1652 {
1653         if (!isMultiColumn(cell))
1654                 return;
1655
1656         row_type const row = cellRow(cell);
1657         col_type const col = cellColumn(cell);
1658         row_type const span = columnSpan(cell);
1659         for (col_type c = 0; c < span; ++c)
1660                 cell_info[row][col + c].multicolumn = CELL_NORMAL;
1661         updateIndexes();
1662 }
1663
1664
1665 void Tabular::unsetMultiRow(idx_type cell)
1666 {
1667         if (!isMultiRow(cell))
1668                 return;
1669
1670         cellInfo(cell).valignment = LYX_VALIGN_TOP;
1671         cellInfo(cell).alignment = LYX_ALIGN_CENTER;
1672         row_type const row = cellRow(cell);
1673         col_type const col = cellColumn(cell);
1674         row_type const span = rowSpan(cell);
1675         for (row_type r = 0; r < span; ++r)
1676                 cell_info[row + r][col].multirow = CELL_NORMAL;
1677         updateIndexes();
1678 }
1679
1680
1681 void Tabular::setRotateCell(idx_type cell, bool flag)
1682 {
1683         cellInfo(cell).rotate = flag;
1684 }
1685
1686
1687 bool Tabular::getRotateCell(idx_type cell) const
1688 {
1689         return cellInfo(cell).rotate;
1690 }
1691
1692
1693 bool Tabular::needRotating() const
1694 {
1695         if (rotate)
1696                 return true;
1697         for (row_type r = 0; r < nrows(); ++r)
1698                 for (col_type c = 0; c < ncols(); ++c)
1699                         if (cell_info[r][c].rotate)
1700                                 return true;
1701         return false;
1702 }
1703
1704
1705 bool Tabular::isLastCell(idx_type cell) const
1706 {
1707         if (cell + 1 < numberofcells)
1708                 return false;
1709         return true;
1710 }
1711
1712
1713 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
1714 {
1715         if (cellRow(cell) == 0)
1716                 return cell;
1717         
1718         col_type const col = cellColumn(cell);
1719         row_type r = cellRow(cell) - 1;
1720         while (r > 0 && cell_info[r][col].multirow == CELL_PART_OF_MULTIROW)
1721                 --r;
1722
1723         return cell_info[r][col].cellno;
1724 }
1725
1726
1727 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
1728 {
1729         row_type const nextrow = cellRow(cell) + rowSpan(cell);
1730         if (nextrow < nrows())
1731                 return cell_info[nextrow][cellColumn(cell)].cellno;
1732         return cell;
1733 }
1734
1735
1736 Tabular::idx_type Tabular::cellIndex(row_type row, col_type column) const
1737 {
1738         LASSERT(column != npos && column < ncols()
1739                 && row != npos && row < nrows(), /**/);
1740         return cell_info[row][column].cellno;
1741 }
1742
1743
1744 void Tabular::setUsebox(idx_type cell, BoxType type)
1745 {
1746         cellInfo(cell).usebox = type;
1747 }
1748
1749
1750 // FIXME: Remove this routine because we cannot insert \parboxes when the user
1751 // adds line breaks, see bug 4886.
1752 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
1753 {
1754         if ((!column_info[cellColumn(cell)].p_width.zero() && !isMultiColumn(cell)) ||
1755                 (isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
1756                 return BOX_NONE;
1757         if (cellInfo(cell).usebox > 1)
1758                 return cellInfo(cell).usebox;
1759         return useParbox(cell);
1760 }
1761
1762
1763 ///
1764 //  This are functions used for the longtable support
1765 ///
1766 void Tabular::setLTHead(row_type row, bool flag, ltType const & hd,
1767                            bool first)
1768 {
1769         if (first) {
1770                 endfirsthead = hd;
1771                 if (hd.set)
1772                         row_info[row].endfirsthead = flag;
1773         } else {
1774                 endhead = hd;
1775                 if (hd.set)
1776                         row_info[row].endhead = flag;
1777         }
1778 }
1779
1780
1781 bool Tabular::getRowOfLTHead(row_type row, ltType & hd) const
1782 {
1783         hd = endhead;
1784         hd.set = haveLTHead();
1785         return row_info[row].endhead;
1786 }
1787
1788
1789 bool Tabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1790 {
1791         hd = endfirsthead;
1792         hd.set = haveLTFirstHead();
1793         return row_info[row].endfirsthead;
1794 }
1795
1796
1797 void Tabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1798                            bool last)
1799 {
1800         if (last) {
1801                 endlastfoot = fd;
1802                 if (fd.set)
1803                         row_info[row].endlastfoot = flag;
1804         } else {
1805                 endfoot = fd;
1806                 if (fd.set)
1807                         row_info[row].endfoot = flag;
1808         }
1809 }
1810
1811
1812 bool Tabular::getRowOfLTFoot(row_type row, ltType & fd) const
1813 {
1814         fd = endfoot;
1815         fd.set = haveLTFoot();
1816         return row_info[row].endfoot;
1817 }
1818
1819
1820 bool Tabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1821 {
1822         fd = endlastfoot;
1823         fd.set = haveLTLastFoot();
1824         return row_info[row].endlastfoot;
1825 }
1826
1827
1828 void Tabular::setLTNewPage(row_type row, bool what)
1829 {
1830         row_info[row].newpage = what;
1831 }
1832
1833
1834 bool Tabular::getLTNewPage(row_type row) const
1835 {
1836         return row_info[row].newpage;
1837 }
1838
1839
1840 bool Tabular::haveLTHead() const
1841 {
1842         for (row_type i = 0; i < nrows(); ++i)
1843                 if (row_info[i].endhead)
1844                         return true;
1845         return false;
1846 }
1847
1848
1849 bool Tabular::haveLTFirstHead() const
1850 {
1851         if (endfirsthead.empty)
1852                 return false;
1853         for (row_type r = 0; r < nrows(); ++r)
1854                 if (row_info[r].endfirsthead)
1855                         return true;
1856         return false;
1857 }
1858
1859
1860 bool Tabular::haveLTFoot() const
1861 {
1862         for (row_type r = 0; r < nrows(); ++r)
1863                 if (row_info[r].endfoot)
1864                         return true;
1865         return false;
1866 }
1867
1868
1869 bool Tabular::haveLTLastFoot() const
1870 {
1871         if (endlastfoot.empty)
1872                 return false;
1873         for (row_type r = 0; r < nrows(); ++r)
1874                 if (row_info[r].endlastfoot)
1875                         return true;
1876         return false;
1877 }
1878
1879
1880 Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
1881 {
1882         idx_type i = getFirstCellInRow(row);
1883         if (what) {
1884                 setMultiColumn(i, numberOfCellsInRow(row));
1885                 setTopLine(i, false);
1886                 setBottomLine(i, false);
1887                 setLeftLine(i, false);
1888                 setRightLine(i, false);
1889         } else {
1890                 unsetMultiColumn(i);
1891                 // When unsetting a caption row, also all existing
1892                 // captions in this row must be dissolved.
1893         }
1894         row_info[row].caption = what;
1895         return i;
1896 }
1897
1898
1899 bool Tabular::ltCaption(row_type row) const
1900 {
1901         return row_info[row].caption;
1902 }
1903
1904
1905 bool Tabular::haveLTCaption() const
1906 {
1907         for (row_type r = 0; r < nrows(); ++r)
1908                 if (row_info[r].caption)
1909                         return true;
1910         return false;
1911 }
1912
1913
1914 // end longtable support functions
1915
1916 void Tabular::setRowAscent(row_type row, int height)
1917 {
1918         if (row >= nrows() || row_info[row].ascent == height)
1919                 return;
1920         row_info[row].ascent = height;
1921 }
1922
1923
1924 void Tabular::setRowDescent(row_type row, int height)
1925 {
1926         if (row >= nrows() || row_info[row].descent == height)
1927                 return;
1928         row_info[row].descent = height;
1929 }
1930
1931
1932 int Tabular::rowAscent(row_type row) const
1933 {
1934         LASSERT(row < nrows(), /**/);
1935         return row_info[row].ascent;
1936 }
1937
1938
1939 int Tabular::rowDescent(row_type row) const
1940 {
1941         LASSERT(row < nrows(), /**/);
1942         return row_info[row].descent;
1943 }
1944
1945
1946 int Tabular::height() const
1947 {
1948         int height = 0;
1949         for (row_type row = 0; row < nrows(); ++row)
1950                 height += rowAscent(row) + rowDescent(row) +
1951                         interRowSpace(row);
1952         return height;
1953 }
1954
1955
1956 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
1957 {
1958         LASSERT(row < nrows(), /**/);
1959         LASSERT(column < ncols(), /**/);
1960         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
1961 }
1962
1963
1964 bool Tabular::isPartOfMultiRow(row_type row, col_type column) const
1965 {
1966         LASSERT(row < nrows(), /**/);
1967         LASSERT(column < ncols(), /**/);
1968         return cell_info[row][column].multirow == CELL_PART_OF_MULTIROW;
1969 }
1970
1971
1972 int Tabular::TeXTopHLine(odocstream & os, row_type row, string const lang) const
1973 {
1974         // we only output complete row lines and the 1st row here, the rest
1975         // is done in Tabular::TeXBottomHLine(...)
1976
1977         // get for each column the topline (if any)
1978         vector<bool> topline;
1979         col_type nset = 0;
1980         for (col_type c = 0; c < ncols(); ++c) {
1981                 topline.push_back(topLine(cellIndex(row, c)));
1982                 // If cell is part of a multirow and not the first cell of the
1983                 // multirow, no line must be drawn.
1984                 if (row != 0)
1985                         if (isMultiRow(cellIndex(row, c))
1986                                 && isMultiRow(cellIndex(row - 1, c)))
1987                                         topline[c] = false;
1988                 if (topline[c])
1989                         ++nset;
1990         }
1991
1992         // do nothing if empty first row, or incomplete row line after
1993         if ((row == 0 && nset == 0) || (row > 0 && nset != ncols()))
1994                 return 0;
1995
1996         // only output complete row lines and the 1st row's clines
1997         if (nset == ncols()) {
1998                 if (use_booktabs) {
1999                         os << (row == 0 ? "\\toprule " : "\\midrule ");
2000                 } else {
2001                         os << "\\hline ";
2002                 }
2003         } else if (row == 0) {
2004                 for (col_type c = 0; c < ncols(); ++c) {
2005                         if (topline[c]) {
2006                                 col_type offset = 0;
2007                                 for (col_type j = 0 ; j < c; ++j)
2008                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2009                                                 ++offset;
2010                                 
2011                                 //babel makes the "-" character an active one, so we have to suppress this here
2012                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
2013                                 if (lang == "slovak" || lang == "czech")
2014                                         os << "\\expandafter" << (use_booktabs ? "\\cmidrule" : "\\cline") 
2015                                         << "\\expandafter{\\expandafter" << c + 1 + offset << "\\string-";
2016                                 else
2017                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 + offset << '-';
2018                                 
2019                                 col_type cstart = c;
2020                                 for ( ; c < ncols() && topline[c]; ++c) {}
2021                                 
2022                                 for (col_type j = cstart ; j < c ; ++j)
2023                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2024                                                 ++offset;
2025                                 
2026                                 os << c + offset << "} ";
2027                         }
2028                 }
2029         }
2030         os << "\n";
2031         return 1;
2032 }
2033
2034
2035 int Tabular::TeXBottomHLine(odocstream & os, row_type row, string const lang) const
2036 {
2037         // we output bottomlines of row r and the toplines of row r+1
2038         // if the latter do not span the whole tabular
2039
2040         // get the bottomlines of row r, and toplines in next row
2041         bool lastrow = row == nrows() - 1;
2042         vector<bool> bottomline, topline;
2043         bool nextrowset = true;
2044         for (col_type c = 0; c < ncols(); ++c) {
2045                 bottomline.push_back(bottomLine(cellIndex(row, c)));
2046                 topline.push_back(!lastrow && topLine(cellIndex(row + 1, c)));
2047                 // If cell is part of a multirow and not the last or first cell of the
2048                 // multirow, no line must be drawn.
2049                 if (!lastrow)
2050                         if (isMultiRow(cellIndex(row, c))
2051                                 && isMultiRow(cellIndex(row + 1, c))) {
2052                                         bottomline[c] = false;
2053                                         topline[c] = false;
2054                                 }
2055                 nextrowset &= topline[c];
2056         }
2057
2058         // combine this row's bottom lines and next row's toplines if necessary
2059         col_type nset = 0;
2060         for (col_type c = 0; c < ncols(); ++c) {
2061                 if (!nextrowset)
2062                         bottomline[c] = bottomline[c] || topline[c];
2063                 if (bottomline[c])
2064                         ++nset;
2065         }
2066
2067         // do nothing if empty, OR incomplete row line with a topline in next row
2068         if (nset == 0 || (nextrowset && nset != ncols()))
2069                 return 0;
2070
2071         if (nset == ncols()) {
2072                 if (use_booktabs)
2073                         os << (lastrow ? "\\bottomrule" : "\\midrule");
2074                 else
2075                         os << "\\hline ";
2076         } else {
2077                 for (col_type c = 0; c < ncols(); ++c) {
2078                         if (bottomline[c]) {
2079                                 col_type offset = 0;
2080                                 for (col_type j = 0 ; j < c; ++j)
2081                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2082                                                 ++offset;
2083                                 
2084                                 //babel makes the "-" character an active one, so we have to suppress this here
2085                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
2086                                 if (lang == "slovak" || lang == "czech")
2087                                         os << "\\expandafter" << (use_booktabs ? "\\cmidrule" : "\\cline")
2088                                         << "\\expandafter{\\expandafter" << c + 1 + offset << "\\string-";
2089                                 else
2090                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 + offset << '-';
2091                                 
2092                                 col_type cstart = c;
2093                                 for ( ; c < ncols() && bottomline[c]; ++c) {}
2094                                 
2095                                 for (col_type j = cstart ; j < c ; ++j)
2096                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2097                                                 ++offset;
2098                                 
2099                                 os << c + offset << "} ";
2100                         }
2101                 }
2102         }
2103         os << "\n";
2104         return 1;
2105 }
2106
2107
2108 int Tabular::TeXCellPreamble(odocstream & os, idx_type cell,
2109                                                          bool & ismulticol, bool & ismultirow) const
2110 {
2111         int ret = 0;
2112         row_type const r = cellRow(cell);
2113         if (is_long_tabular && row_info[r].caption)
2114                 return ret;
2115
2116         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
2117         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
2118         // figure out how to set the lines
2119         // we always set double lines to the right of the cell
2120         col_type const c = cellColumn(cell);
2121         col_type const nextcol = c + columnSpan(cell);
2122         bool colright = columnRightLine(c);
2123         bool colleft = columnLeftLine(c);
2124         bool nextcolleft = nextcol < ncols() && columnLeftLine(nextcol);
2125         bool nextcellleft = nextcol < ncols() 
2126                 && leftLine(cellIndex(r, nextcol));
2127         bool coldouble = colright && nextcolleft;
2128         bool celldouble = rightLine(cell) && nextcellleft;
2129
2130         ismulticol = isMultiColumn(cell)
2131                 || (c == 0 && colleft != leftLine(cell))
2132                 || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
2133                 || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
2134                 || (coldouble != celldouble);
2135
2136         // we center in multicol when no decimal point
2137         ismulticol |= ((column_info[c].alignment == LYX_ALIGN_DECIMAL)
2138                 && (cellInfo(cell).decimal_width == 0));
2139
2140         // up counter by 1 for each decimally aligned col since they use 2 latex cols
2141         int latexcolspan = columnSpan(cell);
2142         for(col_type col = c; col < c + columnSpan(cell); ++col)
2143                 if (column_info[col].alignment == LYX_ALIGN_DECIMAL)
2144                         ++latexcolspan;
2145
2146         if (ismulticol) {
2147                 os << "\\multicolumn{" << latexcolspan << "}{";
2148                 if (c ==0 && leftLine(cell))
2149                         os << '|';
2150                 if (!cellInfo(cell).align_special.empty()) {
2151                         os << cellInfo(cell).align_special;
2152                 } else {
2153                         if (!getPWidth(cell).zero()) {
2154                                 switch (align) {
2155                                 case LYX_ALIGN_LEFT:
2156                                         os << ">{\\raggedright}";
2157                                         break;
2158                                 case LYX_ALIGN_RIGHT:
2159                                         os << ">{\\raggedleft}";
2160                                         break;
2161                                 case LYX_ALIGN_CENTER:
2162                                         os << ">{\\centering}";
2163                                         break;
2164                                 default:
2165                                         break;
2166                                 }
2167                                 switch (valign) {
2168                                 case LYX_VALIGN_TOP:
2169                                         os << 'p';
2170                                         break;
2171                                 case LYX_VALIGN_MIDDLE:
2172                                         os << 'm';
2173                                         break;
2174                                 case LYX_VALIGN_BOTTOM:
2175                                         os << 'b';
2176                                         break;
2177                                 }
2178                                 os << '{'
2179                                    << from_ascii(getPWidth(cell).asLatexString())
2180                                    << '}';
2181                         } else {
2182                                 switch (align) {
2183                                 case LYX_ALIGN_LEFT:
2184                                         os << 'l';
2185                                         break;
2186                                 case LYX_ALIGN_RIGHT:
2187                                         os << 'r';
2188                                         break;
2189                                 default:
2190                                         os << 'c';
2191                                         break;
2192                                 }
2193                         } // end if else !getPWidth
2194                 } // end if else !cellinfo_of_cell
2195                 if (rightLine(cell) || nextcellleft)
2196                         os << '|';
2197                 if (celldouble)
2198                         // add extra vertical line if we want a double one
2199                         os << '|';
2200                 os << "}{";
2201         } // end if ismulticol
2202
2203         // we only need code for the first multirow cell
2204         ismultirow = isMultiRow(cell);
2205         if (ismultirow) {
2206                 os << "\\multirow{" << rowSpan(cell) << "}{";
2207                 if (!getPWidth(cell).zero())
2208                         os << from_ascii(getPWidth(cell).asLatexString());
2209                 else
2210                         // we need to set a default value
2211                         os << "*";
2212                 os << "}{";
2213         } // end if ismultirow
2214
2215         if (getRotateCell(cell)) {
2216                 os << "\\begin{sideways}\n";
2217                 ++ret;
2218         }
2219         if (getUsebox(cell) == BOX_PARBOX) {
2220                 os << "\\parbox[";
2221                 switch (valign) {
2222                 case LYX_VALIGN_TOP:
2223                         os << 't';
2224                         break;
2225                 case LYX_VALIGN_MIDDLE:
2226                         os << 'c';
2227                         break;
2228                 case LYX_VALIGN_BOTTOM:
2229                         os << 'b';
2230                         break;
2231                 }
2232                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2233                    << "}{";
2234         } else if (getUsebox(cell) == BOX_MINIPAGE) {
2235                 os << "\\begin{minipage}[";
2236                 switch (valign) {
2237                 case LYX_VALIGN_TOP:
2238                         os << 't';
2239                         break;
2240                 case LYX_VALIGN_MIDDLE:
2241                         os << 'm';
2242                         break;
2243                 case LYX_VALIGN_BOTTOM:
2244                         os << 'b';
2245                         break;
2246                 }
2247                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2248                    << "}\n";
2249                 ++ret;
2250         }
2251         return ret;
2252 }
2253
2254
2255 int Tabular::TeXCellPostamble(odocstream & os, idx_type cell,
2256                                                           bool ismulticol, bool ismultirow) const
2257 {
2258         int ret = 0;
2259         row_type const r = cellRow(cell);
2260         if (is_long_tabular && row_info[r].caption)
2261                 return ret;
2262
2263         // usual cells
2264         if (getUsebox(cell) == BOX_PARBOX)
2265                 os << '}';
2266         else if (getUsebox(cell) == BOX_MINIPAGE) {
2267                 os << "%\n\\end{minipage}";
2268                 ret += 2;
2269         }
2270         if (getRotateCell(cell)) {
2271                 os << "%\n\\end{sideways}";
2272                 ++ret;
2273         }
2274         if (ismultirow)
2275                 os << '}';
2276         if (ismulticol)
2277                 os << '}';
2278
2279         return ret;
2280 }
2281
2282
2283 int Tabular::TeXLongtableHeaderFooter(odocstream & os,
2284                                          OutputParams const & runparams) const
2285 {
2286         if (!is_long_tabular)
2287                 return 0;
2288
2289         int ret = 0;
2290         // caption handling
2291         // the caption must be output before the headers
2292         if (haveLTCaption()) {
2293                 for (row_type r = 0; r < nrows(); ++r) {
2294                         if (row_info[r].caption) {
2295                                 ret += TeXRow(os, r, runparams);
2296                         }
2297                 }
2298         }
2299         // output first header info
2300         // first header must be output before the header, otherwise the
2301         // correct caption placement becomes really weird
2302         if (haveLTFirstHead()) {
2303                 if (endfirsthead.topDL) {
2304                         os << "\\hline\n";
2305                         ++ret;
2306                 }
2307                 for (row_type r = 0; r < nrows(); ++r) {
2308                         if (row_info[r].endfirsthead) {
2309                                 ret += TeXRow(os, r, runparams);
2310                         }
2311                 }
2312                 if (endfirsthead.bottomDL) {
2313                         os << "\\hline\n";
2314                         ++ret;
2315                 }
2316                 os << "\\endfirsthead\n";
2317                 ++ret;
2318         }
2319         // output header info
2320         if (haveLTHead()) {
2321                 if (endfirsthead.empty && !haveLTFirstHead()) {
2322                         os << "\\endfirsthead\n";
2323                         ++ret;
2324                 }
2325                 if (endhead.topDL) {
2326                         os << "\\hline\n";
2327                         ++ret;
2328                 }
2329                 for (row_type r = 0; r < nrows(); ++r) {
2330                         if (row_info[r].endhead) {
2331                                 ret += TeXRow(os, r, runparams);
2332                         }
2333                 }
2334                 if (endhead.bottomDL) {
2335                         os << "\\hline\n";
2336                         ++ret;
2337                 }
2338                 os << "\\endhead\n";
2339                 ++ret;
2340         }
2341         // output footer info
2342         if (haveLTFoot()) {
2343                 if (endfoot.topDL) {
2344                         os << "\\hline\n";
2345                         ++ret;
2346                 }
2347                 for (row_type r = 0; r < nrows(); ++r) {
2348                         if (row_info[r].endfoot) {
2349                                 ret += TeXRow(os, r, runparams);
2350                         }
2351                 }
2352                 if (endfoot.bottomDL) {
2353                         os << "\\hline\n";
2354                         ++ret;
2355                 }
2356                 os << "\\endfoot\n";
2357                 ++ret;
2358                 if (endlastfoot.empty && !haveLTLastFoot()) {
2359                         os << "\\endlastfoot\n";
2360                         ++ret;
2361                 }
2362         }
2363         // output lastfooter info
2364         if (haveLTLastFoot()) {
2365                 if (endlastfoot.topDL) {
2366                         os << "\\hline\n";
2367                         ++ret;
2368                 }
2369                 for (row_type r = 0; r < nrows(); ++r) {
2370                         if (row_info[r].endlastfoot) {
2371                                 ret += TeXRow(os, r, runparams);
2372                         }
2373                 }
2374                 if (endlastfoot.bottomDL) {
2375                         os << "\\hline\n";
2376                         ++ret;
2377                 }
2378                 os << "\\endlastfoot\n";
2379                 ++ret;
2380         }
2381         return ret;
2382 }
2383
2384
2385 bool Tabular::isValidRow(row_type row) const
2386 {
2387         if (!is_long_tabular)
2388                 return true;
2389         return !row_info[row].endhead && !row_info[row].endfirsthead
2390                 && !row_info[row].endfoot && !row_info[row].endlastfoot
2391                 && !row_info[row].caption;
2392 }
2393
2394
2395 int Tabular::TeXRow(odocstream & os, row_type row,
2396                        OutputParams const & runparams) const
2397 {
2398         idx_type cell = cellIndex(row, 0);
2399         shared_ptr<InsetTableCell> inset = cellInset(cell);
2400         Paragraph const & par = inset->paragraphs().front();
2401         string const lang = par.getParLanguage(buffer().params())->lang();
2402
2403         //output the top line
2404         int ret = TeXTopHLine(os, row, lang);
2405
2406         if (row_info[row].top_space_default) {
2407                 if (use_booktabs)
2408                         os << "\\addlinespace\n";
2409                 else
2410                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2411                 ++ret;
2412         } else if(!row_info[row].top_space.zero()) {
2413                 if (use_booktabs)
2414                         os << "\\addlinespace["
2415                            << from_ascii(row_info[row].top_space.asLatexString())
2416                            << "]\n";
2417                 else {
2418                         os << "\\noalign{\\vskip"
2419                            << from_ascii(row_info[row].top_space.asLatexString())
2420                            << "}\n";
2421                 }
2422                 ++ret;
2423         }
2424         bool ismulticol = false;
2425         bool ismultirow = false;
2426         for (col_type c = 0; c < ncols(); ++c) {
2427                 if (isPartOfMultiColumn(row, c))
2428                         continue;
2429                         
2430                 if (isPartOfMultiRow(row, c) && 
2431                         column_info[c].alignment != LYX_ALIGN_DECIMAL) {
2432                         os << " & "; 
2433                         continue;
2434                 }
2435
2436                 cell = cellIndex(row, c);
2437                 ret += TeXCellPreamble(os, cell, ismulticol, ismultirow);
2438                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2439
2440                 Paragraph const & par = inset->paragraphs().front();
2441                 bool rtl = par.isRTL(buffer().params())
2442                         && !par.empty()
2443                         && getPWidth(cell).zero();
2444
2445                 if (rtl) {
2446                         string const lang =
2447                                 par.getParLanguage(buffer().params())->lang();
2448                         if (lang == "farsi")
2449                                 os << "\\textFR{";
2450                         else if (lang == "arabic_arabi")
2451                                 os << "\\textAR{";
2452                         // currently, remaning RTL languages are
2453                         // arabic_arabtex and hebrew
2454                         else
2455                                 os << "\\R{";
2456                 }
2457                 // pass to the OutputParams that we are in a cell and
2458                 // which alignment we have set.
2459                 // InsetNewline needs this context information.
2460                 OutputParams newrp(runparams);
2461                 newrp.inTableCell = (getAlignment(cell) == LYX_ALIGN_BLOCK)
2462                                     ? OutputParams::PLAIN
2463                                     : OutputParams::ALIGNED;
2464
2465                 if (getAlignment(cell) == LYX_ALIGN_DECIMAL
2466                         && cellInfo(cell).decimal_width != 0) {
2467                         // copy cell and split in 2
2468                         InsetTableCell head = InsetTableCell(*cellInset(cell).get());
2469                         head.getText(0)->setMacrocontextPosition(
2470                                 cellInset(cell)->getText(0)->macrocontextPosition());
2471                         head.setBuffer(buffer());
2472                         bool hassep = false;
2473                         InsetTableCell tail = splitCell(head, column_info[c].decimal_point, hassep);
2474                         head.latex(os, newrp);
2475                         os << '&';
2476                         ret += tail.latex(os, newrp);
2477                 } else if (!isPartOfMultiRow(row, c))
2478                         ret += inset->latex(os, newrp);
2479
2480                 runparams.encoding = newrp.encoding;
2481                 if (rtl)
2482                         os << '}';
2483
2484                 ret += TeXCellPostamble(os, cell, ismulticol, ismultirow);
2485                 if (cell != getLastCellInRow(row)) { // not last cell in row
2486                         os << " & ";
2487                 }
2488         }
2489         if (row_info[row].caption && !endfirsthead.empty && !haveLTFirstHead())
2490                 // if no first header and no empty first header is used,
2491                 // the caption needs to be terminated by \endfirsthead
2492                 // (bug 6057)
2493                 os << "\\endfirsthead";
2494         else
2495                 os << "\\tabularnewline";
2496         if (row_info[row].bottom_space_default) {
2497                 if (use_booktabs)
2498                         os << "\\addlinespace";
2499                 else
2500                         os << "[\\doublerulesep]";
2501         } else if (!row_info[row].bottom_space.zero()) {
2502                 if (use_booktabs)
2503                         os << "\\addlinespace";
2504                 os << '['
2505                    << from_ascii(row_info[row].bottom_space.asLatexString())
2506                    << ']';
2507         }
2508         os << '\n';
2509         ++ret;
2510
2511         //output the bottom line
2512         ret += TeXBottomHLine(os, row, lang);
2513
2514         if (row_info[row].interline_space_default) {
2515                 if (use_booktabs)
2516                         os << "\\addlinespace\n";
2517                 else
2518                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2519                 ++ret;
2520         } else if (!row_info[row].interline_space.zero()) {
2521                 if (use_booktabs)
2522                         os << "\\addlinespace["
2523                            << from_ascii(row_info[row].interline_space.asLatexString())
2524                            << "]\n";
2525                 else
2526                         os << "\\noalign{\\vskip"
2527                            << from_ascii(row_info[row].interline_space.asLatexString())
2528                            << "}\n";
2529                 ++ret;
2530         }
2531         return ret;
2532 }
2533
2534
2535 int Tabular::latex(odocstream & os, OutputParams const & runparams) const
2536 {
2537         int ret = 0;
2538
2539         //+---------------------------------------------------------------------
2540         //+                      first the opening preamble                    +
2541         //+---------------------------------------------------------------------
2542
2543         if (rotate) {
2544                 os << "\\begin{sideways}\n";
2545                 ++ret;
2546         }
2547         if (is_long_tabular) {
2548                 os << "\\begin{longtable}";
2549                 switch (longtabular_alignment) {
2550                 case LYX_LONGTABULAR_ALIGN_LEFT:
2551                         os << "[l]";
2552                         break;
2553                 case LYX_LONGTABULAR_ALIGN_CENTER:
2554                         break;
2555                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2556                         os << "[r]";
2557                         break;
2558                 }
2559         } else {
2560                 os << "\\begin{tabular}";
2561                 switch (tabular_valignment) {
2562                 case LYX_VALIGN_TOP:
2563                         os << "[t]";
2564                         break;
2565                 case LYX_VALIGN_MIDDLE:
2566                         break;
2567                 case LYX_VALIGN_BOTTOM:
2568                         os << "[b]";
2569                         break;
2570                 }
2571         }
2572         
2573         os << "{";
2574
2575         for (col_type c = 0; c < ncols(); ++c) {
2576                 if (columnLeftLine(c))
2577                         os << '|';
2578                 if (!column_info[c].align_special.empty()) {
2579                         os << column_info[c].align_special;
2580                 } else {
2581                         if (!column_info[c].p_width.zero()) {
2582                                 switch (column_info[c].alignment) {
2583                                 case LYX_ALIGN_LEFT:
2584                                         os << ">{\\raggedright}";
2585                                         break;
2586                                 case LYX_ALIGN_RIGHT:
2587                                         os << ">{\\raggedleft}";
2588                                         break;
2589                                 case LYX_ALIGN_CENTER:
2590                                         os << ">{\\centering}";
2591                                         break;
2592                                 case LYX_ALIGN_NONE:
2593                                 case LYX_ALIGN_BLOCK:
2594                                 case LYX_ALIGN_LAYOUT:
2595                                 case LYX_ALIGN_SPECIAL:
2596                                 case LYX_ALIGN_DECIMAL:
2597                                         break;
2598                                 }
2599
2600                                 switch (column_info[c].valignment) {
2601                                 case LYX_VALIGN_TOP:
2602                                         os << 'p';
2603                                         break;
2604                                 case LYX_VALIGN_MIDDLE:
2605                                         os << 'm';
2606                                         break;
2607                                 case LYX_VALIGN_BOTTOM:
2608                                         os << 'b';
2609                                         break;
2610                         }
2611                                 os << '{'
2612                                    << from_ascii(column_info[c].p_width.asLatexString())
2613                                    << '}';
2614                         } else {
2615                                 switch (column_info[c].alignment) {
2616                                 case LYX_ALIGN_LEFT:
2617                                         os << 'l';
2618                                         break;
2619                                 case LYX_ALIGN_RIGHT:
2620                                         os << 'r';
2621                                         break;
2622                                 case LYX_ALIGN_DECIMAL:
2623                                         os << "r@{\\extracolsep{0pt}" << column_info[c].decimal_point << "}l";
2624                                         break;
2625                                 default:
2626                                         os << 'c';
2627                                         break;
2628                                 }
2629                         } // end if else !column_info[i].p_width
2630                 } // end if else !column_info[i].align_special
2631                 if (columnRightLine(c))
2632                         os << '|';
2633         }
2634         os << "}\n";
2635         ++ret;
2636
2637         ret += TeXLongtableHeaderFooter(os, runparams);
2638
2639         //+---------------------------------------------------------------------
2640         //+                      the single row and columns (cells)            +
2641         //+---------------------------------------------------------------------
2642
2643         for (row_type r = 0; r < nrows(); ++r) {
2644                 if (isValidRow(r)) {
2645                         ret += TeXRow(os, r, runparams);
2646                         if (is_long_tabular && row_info[r].newpage) {
2647                                 os << "\\newpage\n";
2648                                 ++ret;
2649                         }
2650                 }
2651         }
2652
2653         //+---------------------------------------------------------------------
2654         //+                      the closing of the tabular                    +
2655         //+---------------------------------------------------------------------
2656
2657         if (is_long_tabular)
2658                 os << "\\end{longtable}";
2659         else
2660                 os << "\\end{tabular}";
2661         if (rotate) {
2662                 os << "\n\\end{sideways}";
2663                 ++ret;
2664         }
2665
2666         return ret;
2667 }
2668
2669
2670 int Tabular::docbookRow(odocstream & os, row_type row,
2671                            OutputParams const & runparams) const
2672 {
2673         int ret = 0;
2674         idx_type cell = getFirstCellInRow(row);
2675
2676         os << "<row>\n";
2677         for (col_type c = 0; c < ncols(); ++c) {
2678                 if (isPartOfMultiColumn(row, c))
2679                         continue;
2680
2681                 os << "<entry align=\"";
2682                 switch (getAlignment(cell)) {
2683                 case LYX_ALIGN_LEFT:
2684                         os << "left";
2685                         break;
2686                 case LYX_ALIGN_RIGHT:
2687                         os << "right";
2688                         break;
2689                 default:
2690                         os << "center";
2691                         break;
2692                 }
2693
2694                 os << "\" valign=\"";
2695                 switch (getVAlignment(cell)) {
2696                 case LYX_VALIGN_TOP:
2697                         os << "top";
2698                         break;
2699                 case LYX_VALIGN_BOTTOM:
2700                         os << "bottom";
2701                         break;
2702                 case LYX_VALIGN_MIDDLE:
2703                         os << "middle";
2704                 }
2705                 os << '"';
2706
2707                 if (isMultiColumn(cell)) {
2708                         os << " namest=\"col" << c << "\" ";
2709                         os << "nameend=\"col" << c + columnSpan(cell) - 1 << '"';
2710                 }
2711
2712                 os << '>';
2713                 ret += cellInset(cell)->docbook(os, runparams);
2714                 os << "</entry>\n";
2715                 ++cell;
2716         }
2717         os << "</row>\n";
2718         return ret;
2719 }
2720
2721
2722 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2723 {
2724         int ret = 0;
2725
2726         //+---------------------------------------------------------------------
2727         //+                      first the opening preamble                    +
2728         //+---------------------------------------------------------------------
2729
2730         os << "<tgroup cols=\"" << ncols()
2731            << "\" colsep=\"1\" rowsep=\"1\">\n";
2732
2733         for (col_type c = 0; c < ncols(); ++c) {
2734                 os << "<colspec colname=\"col" << c << "\" align=\"";
2735                 switch (column_info[c].alignment) {
2736                 case LYX_ALIGN_LEFT:
2737                         os << "left";
2738                         break;
2739                 case LYX_ALIGN_RIGHT:
2740                         os << "right";
2741                         break;
2742                 default:
2743                         os << "center";
2744                         break;
2745                 }
2746                 os << '"';
2747                 if (runparams.flavor == OutputParams::XML)
2748                         os << '/';
2749                 os << ">\n";
2750                 ++ret;
2751         }
2752
2753         //+---------------------------------------------------------------------
2754         //+                      Long Tabular case                             +
2755         //+---------------------------------------------------------------------
2756
2757         // output caption info
2758         if (haveLTCaption()) {
2759                 os << "<caption>\n";
2760                 ++ret;
2761                 for (row_type r = 0; r < nrows(); ++r) {
2762                         if (row_info[r].caption) {
2763                                 ret += docbookRow(os, r, runparams);
2764                         }
2765                 }
2766                 os << "</caption>\n";
2767                 ++ret;
2768         }
2769         // output header info
2770         if (haveLTHead() || haveLTFirstHead()) {
2771                 os << "<thead>\n";
2772                 ++ret;
2773                 for (row_type r = 0; r < nrows(); ++r) {
2774                         if (row_info[r].endhead || row_info[r].endfirsthead) {
2775                                 ret += docbookRow(os, r, runparams);
2776                         }
2777                 }
2778                 os << "</thead>\n";
2779                 ++ret;
2780         }
2781         // output footer info
2782         if (haveLTFoot() || haveLTLastFoot()) {
2783                 os << "<tfoot>\n";
2784                 ++ret;
2785                 for (row_type r = 0; r < nrows(); ++r) {
2786                         if (row_info[r].endfoot || row_info[r].endlastfoot) {
2787                                 ret += docbookRow(os, r, runparams);
2788                         }
2789                 }
2790                 os << "</tfoot>\n";
2791                 ++ret;
2792         }
2793
2794         //+---------------------------------------------------------------------
2795         //+                      the single row and columns (cells)            +
2796         //+---------------------------------------------------------------------
2797
2798         os << "<tbody>\n";
2799         ++ret;
2800         for (row_type r = 0; r < nrows(); ++r) {
2801                 if (isValidRow(r)) {
2802                         ret += docbookRow(os, r, runparams);
2803                 }
2804         }
2805         os << "</tbody>\n";
2806         ++ret;
2807         //+---------------------------------------------------------------------
2808         //+                      the closing of the tabular                    +
2809         //+---------------------------------------------------------------------
2810
2811         os << "</tgroup>";
2812         ++ret;
2813
2814         return ret;
2815 }
2816
2817
2818 docstring Tabular::xhtmlRow(XHTMLStream & xs, row_type row,
2819                            OutputParams const & runparams) const
2820 {
2821         docstring ret;
2822         idx_type cell = getFirstCellInRow(row);
2823
2824         xs << html::StartTag("tr");
2825         for (col_type c = 0; c < ncols(); ++c) {
2826                 if (isPartOfMultiColumn(row, c))
2827                         continue;
2828
2829                 stringstream attr;
2830                 attr << "align='";
2831                 switch (getAlignment(cell)) {
2832                 case LYX_ALIGN_LEFT:
2833                         attr << "left";
2834                         break;
2835                 case LYX_ALIGN_RIGHT:
2836                         attr << "right";
2837                         break;
2838                 default:
2839                         attr << "center";
2840                         break;
2841                 }
2842                 attr << "'";
2843                 attr << " valign='";
2844                 switch (getVAlignment(cell)) {
2845                 case LYX_VALIGN_TOP:
2846                         attr << "top";
2847                         break;
2848                 case LYX_VALIGN_BOTTOM:
2849                         attr << "bottom";
2850                         break;
2851                 case LYX_VALIGN_MIDDLE:
2852                         attr << "middle";
2853                 }
2854                 attr << "'";
2855
2856                 if (isMultiColumn(cell))
2857                         attr << " colspan='" << columnSpan(cell) << "'";
2858
2859                 xs << html::StartTag("td", attr.str());
2860                 ret += cellInset(cell)->xhtml(xs, runparams);
2861                 xs << html::EndTag("td");
2862                 ++cell;
2863         }
2864         xs << html::EndTag("tr");
2865         return ret;
2866 }
2867
2868
2869 docstring Tabular::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
2870 {
2871         docstring ret;
2872         // It's unclear to me if we need to mess with the long table stuff. 
2873         // We can borrow that too from docbook, if so.
2874
2875         xs << html::StartTag("tbody");
2876         for (row_type r = 0; r < nrows(); ++r) {
2877                 if (isValidRow(r)) {
2878                         ret += xhtmlRow(xs, r, runparams);
2879                 }
2880         }
2881         xs << html::EndTag("tbody");
2882         return ret;
2883 }
2884
2885
2886 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2887                                    vector<unsigned int> const & clen) const
2888 {
2889         idx_type const fcell = getFirstCellInRow(row);
2890         idx_type const n = numberOfCellsInRow(row) + fcell;
2891         idx_type tmp = 0;
2892
2893         for (idx_type i = fcell; i < n; ++i) {
2894                 if (topLine(i)) {
2895                         ++tmp;
2896                         break;
2897                 }
2898         }
2899         if (!tmp)
2900                 return false;
2901
2902         char_type ch;
2903         for (idx_type i = fcell; i < n; ++i) {
2904                 if (topLine(i)) {
2905                         if (leftLine(i))
2906                                 os << "+-";
2907                         else
2908                                 os << "--";
2909                         ch = '-';
2910                 } else {
2911                         os << "  ";
2912                         ch = ' ';
2913                 }
2914                 col_type column = cellColumn(i);
2915                 int len = clen[column];
2916                 while (column < ncols() - 1
2917                        && isPartOfMultiColumn(row, ++column))
2918                         len += clen[column] + 4;
2919                 os << docstring(len, ch);
2920                 if (topLine(i)) {
2921                         if (rightLine(i))
2922                                 os << "-+";
2923                         else
2924                                 os << "--";
2925                 } else {
2926                         os << "  ";
2927                 }
2928         }
2929         os << endl;
2930         return true;
2931 }
2932
2933
2934 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2935                                       vector<unsigned int> const & clen) const
2936 {
2937         idx_type const fcell = getFirstCellInRow(row);
2938         idx_type const n = numberOfCellsInRow(row) + fcell;
2939         idx_type tmp = 0;
2940
2941         for (idx_type i = fcell; i < n; ++i) {
2942                 if (bottomLine(i)) {
2943                         ++tmp;
2944                         break;
2945                 }
2946         }
2947         if (!tmp)
2948                 return false;
2949
2950         char_type ch;
2951         for (idx_type i = fcell; i < n; ++i) {
2952                 if (bottomLine(i)) {
2953                         if (leftLine(i))
2954                                 os << "+-";
2955                         else
2956                                 os << "--";
2957                         ch = '-';
2958                 } else {
2959                         os << "  ";
2960                         ch = ' ';
2961                 }
2962                 col_type column = cellColumn(i);
2963                 int len = clen[column];
2964                 while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
2965                         len += clen[column] + 4;
2966                 os << docstring(len, ch);
2967                 if (bottomLine(i)) {
2968                         if (rightLine(i))
2969                                 os << "-+";
2970                         else
2971                                 os << "--";
2972                 } else {
2973                         os << "  ";
2974                 }
2975         }
2976         os << endl;
2977         return true;
2978 }
2979
2980
2981 void Tabular::plaintextPrintCell(odocstream & os,
2982                                OutputParams const & runparams,
2983                                idx_type cell, row_type row, col_type column,
2984                                vector<unsigned int> const & clen,
2985                                bool onlydata) const
2986 {
2987         odocstringstream sstr;
2988         cellInset(cell)->plaintext(sstr, runparams);
2989
2990         if (onlydata) {
2991                 os << sstr.str();
2992                 return;
2993         }
2994
2995         if (leftLine(cell))
2996                 os << "| ";
2997         else
2998                 os << "  ";
2999
3000         unsigned int len1 = sstr.str().length();
3001         unsigned int len2 = clen[column];
3002         while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3003                 len2 += clen[column] + 4;
3004         len2 -= len1;
3005
3006         switch (getAlignment(cell)) {
3007         default:
3008         case LYX_ALIGN_LEFT:
3009                 len1 = 0;
3010                 break;
3011         case LYX_ALIGN_RIGHT:
3012                 len1 = len2;
3013                 len2 = 0;
3014                 break;
3015         case LYX_ALIGN_CENTER:
3016                 len1 = len2 / 2;
3017                 len2 -= len1;
3018                 break;
3019         }
3020
3021         os << docstring(len1, ' ') << sstr.str()
3022            << docstring(len2, ' ');
3023
3024         if (rightLine(cell))
3025                 os << " |";
3026         else
3027                 os << "  ";
3028 }
3029
3030
3031 void Tabular::plaintext(odocstream & os,
3032                            OutputParams const & runparams, int const depth,
3033                            bool onlydata, char_type delim) const
3034 {
3035         // first calculate the width of the single columns
3036         vector<unsigned int> clen(ncols());
3037
3038         if (!onlydata) {
3039                 // first all non multicolumn cells!
3040                 for (col_type c = 0; c < ncols(); ++c) {
3041                         clen[c] = 0;
3042                         for (row_type r = 0; r < nrows(); ++r) {
3043                                 idx_type cell = cellIndex(r, c);
3044                                 if (isMultiColumn(cell))
3045                                         continue;
3046                                 odocstringstream sstr;
3047                                 cellInset(cell)->plaintext(sstr, runparams);
3048                                 if (clen[c] < sstr.str().length())
3049                                         clen[c] = sstr.str().length();
3050                         }
3051                 }
3052                 // then all multicolumn cells!
3053                 for (col_type c = 0; c < ncols(); ++c) {
3054                         for (row_type r = 0; r < nrows(); ++r) {
3055                                 idx_type cell = cellIndex(r, c);
3056                                 if (cell_info[r][c].multicolumn != CELL_BEGIN_OF_MULTICOLUMN)
3057                                         continue;
3058                                 odocstringstream sstr;
3059                                 cellInset(cell)->plaintext(sstr, runparams);
3060                                 int len = int(sstr.str().length());
3061                                 idx_type const n = columnSpan(cell);
3062                                 for (col_type k = c; len > 0 && k < c + n - 1; ++k)
3063                                         len -= clen[k];
3064                                 if (len > int(clen[c + n - 1]))
3065                                         clen[c + n - 1] = len;
3066                         }
3067                 }
3068         }
3069         idx_type cell = 0;
3070         for (row_type r = 0; r < nrows(); ++r) {
3071                 if (!onlydata && plaintextTopHLine(os, r, clen))
3072                         os << docstring(depth * 2, ' ');
3073                 for (col_type c = 0; c < ncols(); ++c) {
3074                         if (isPartOfMultiColumn(r, c))
3075                                 continue;
3076                         if (onlydata && c > 0)
3077                                 // we don't use operator<< for single UCS4 character.
3078                                 // see explanation in docstream.h
3079                                 os.put(delim);
3080                         plaintextPrintCell(os, runparams, cell, r, c, clen, onlydata);
3081                         ++cell;
3082                 }
3083                 os << endl;
3084                 if (!onlydata) {
3085                         os << docstring(depth * 2, ' ');
3086                         if (plaintextBottomHLine(os, r, clen))
3087                                 os << docstring(depth * 2, ' ');
3088                 }
3089         }
3090 }
3091
3092
3093 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
3094 {
3095         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
3096 }
3097
3098
3099 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
3100                                                col_type column) const
3101 {
3102         return cell_info[row][column].inset;
3103 }
3104
3105
3106 void Tabular::setCellInset(row_type row, col_type column,
3107                               shared_ptr<InsetTableCell> ins) const
3108 {
3109         CellData & cd = cell_info[row][column];
3110         cd.inset = ins;
3111 }
3112
3113
3114 void Tabular::validate(LaTeXFeatures & features) const
3115 {
3116         features.require("NeedTabularnewline");
3117         if (use_booktabs)
3118                 features.require("booktabs");
3119         if (is_long_tabular)
3120                 features.require("longtable");
3121         if (needRotating())
3122                 features.require("rotating");
3123         for (idx_type cell = 0; cell < numberofcells; ++cell) {
3124                 if (isMultiRow(cell))
3125                         features.require("multirow");
3126                 if (getVAlignment(cell) != LYX_VALIGN_TOP
3127                     || !getPWidth(cell).zero())
3128                         features.require("array");
3129                 cellInset(cell)->validate(features);
3130         }
3131 }
3132
3133
3134 Tabular::BoxType Tabular::useParbox(idx_type cell) const
3135 {
3136         ParagraphList const & parlist = cellInset(cell)->paragraphs();
3137         ParagraphList::const_iterator cit = parlist.begin();
3138         ParagraphList::const_iterator end = parlist.end();
3139
3140         for (; cit != end; ++cit)
3141                 for (int i = 0; i < cit->size(); ++i)
3142                         if (cit->isNewline(i))
3143                                 return BOX_PARBOX;
3144
3145         return BOX_NONE;
3146 }
3147
3148
3149 /////////////////////////////////////////////////////////////////////
3150 //
3151 // InsetTableCell
3152 //
3153 /////////////////////////////////////////////////////////////////////
3154
3155 InsetTableCell::InsetTableCell(Buffer * buf)
3156         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
3157           contentAlign(LYX_ALIGN_CENTER)
3158 {}
3159
3160
3161 bool InsetTableCell::forcePlainLayout(idx_type) const
3162 {
3163         return !isFixedWidth;
3164 }
3165
3166
3167 bool InsetTableCell::allowParagraphCustomization(idx_type) const
3168 {
3169         return isFixedWidth;
3170 }
3171
3172
3173 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
3174         FuncStatus & status) const
3175 {
3176         bool enabled;
3177         switch (cmd.action()) {
3178         case LFUN_LAYOUT:
3179                 enabled = !forcePlainLayout();
3180                 break;
3181         case LFUN_LAYOUT_PARAGRAPH:
3182                 enabled = allowParagraphCustomization();
3183                 break;
3184         default:
3185                 return InsetText::getStatus(cur, cmd, status);
3186         }
3187         status.setEnabled(enabled);
3188         return true;
3189 }
3190
3191 docstring InsetTableCell::asString(bool intoInsets) 
3192 {
3193         docstring retval;
3194         if (paragraphs().empty())
3195                 return retval;
3196         ParagraphList::const_iterator it = paragraphs().begin();
3197         ParagraphList::const_iterator en = paragraphs().end();
3198         bool first = true;
3199         for (; it != en; ++it) {
3200                 if (!first)
3201                         retval += "\n";
3202                 else
3203                         first = false;
3204                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
3205         }
3206         return retval;
3207 }
3208
3209
3210 docstring InsetTableCell::xhtml(XHTMLStream & xs, OutputParams const & rp) const
3211 {
3212         if (!isFixedWidth)
3213                 return InsetText::insetAsXHTML(xs, rp, InsetText::JustText);
3214         return InsetText::xhtml(xs, rp);
3215 }
3216
3217
3218
3219 /////////////////////////////////////////////////////////////////////
3220 //
3221 // InsetTabular
3222 //
3223 /////////////////////////////////////////////////////////////////////
3224
3225 InsetTabular::InsetTabular(Buffer * buf, row_type rows,
3226                            col_type columns)
3227         : Inset(buf), tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
3228         rowselect_(false), colselect_(false)
3229 {
3230 }
3231
3232
3233 InsetTabular::InsetTabular(InsetTabular const & tab)
3234         : Inset(tab), tabular(tab.tabular),  scx_(0)
3235 {
3236 }
3237
3238
3239 InsetTabular::~InsetTabular()
3240 {
3241         hideDialogs("tabular", this);
3242 }
3243
3244
3245 void InsetTabular::setBuffer(Buffer & buf)
3246 {
3247         tabular.setBuffer(buf);
3248         Inset::setBuffer(buf);
3249 }
3250
3251
3252 bool InsetTabular::insetAllowed(InsetCode code) const
3253 {
3254         switch (code) {
3255         case FLOAT_CODE:
3256         case MARGIN_CODE:
3257         case MATHMACRO_CODE:
3258         case WRAP_CODE:
3259                 return false;
3260
3261         case CAPTION_CODE:
3262                 return tabular.is_long_tabular;
3263
3264         default:
3265                 return true;
3266         }
3267 }
3268
3269
3270 void InsetTabular::write(ostream & os) const
3271 {
3272         os << "Tabular" << endl;
3273         tabular.write(os);
3274 }
3275
3276
3277 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
3278 {
3279         // FIXME: depending on the selection state, we could offer a different menu.
3280         return from_ascii("context-tabular");
3281 }
3282
3283
3284 void InsetTabular::read(Lexer & lex)
3285 {
3286         //bool const old_format = (lex.getString() == "\\LyXTable");
3287
3288         tabular.read(lex);
3289
3290         //if (old_format)
3291         //      return;
3292
3293         lex.next();
3294         string token = lex.getString();
3295         while (lex && token != "\\end_inset") {
3296                 lex.next();
3297                 token = lex.getString();
3298         }
3299         if (!lex)
3300                 lex.printError("Missing \\end_inset at this point. ");
3301 }
3302
3303
3304 int InsetTabular::rowFromY(Cursor & cur, int y) const
3305 {
3306         // top y coordinate of tabular
3307         int h = yo(cur.bv()) - tabular.rowAscent(0);
3308         row_type r = 0;
3309         for (; r < tabular.nrows() && y > h; ++r)
3310                 h += tabular.rowAscent(r) + tabular.rowDescent(r)
3311                 + tabular.interRowSpace(r);
3312
3313         return r - 1;
3314 }
3315
3316
3317 int InsetTabular::columnFromX(Cursor & cur, int x) const
3318 {
3319         // left x coordinate of tabular
3320         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3321         col_type c = 0;
3322         for (; c < tabular.ncols() && x > w; ++c)
3323                 w += tabular.cellWidth(c);
3324         return c - 1;
3325 }
3326
3327
3328 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3329 {
3330         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3331         //      mi.base.textwidth << "\n";
3332         if (!mi.base.bv) {
3333                 LYXERR0("need bv");
3334                 LASSERT(false, /**/);
3335         }
3336
3337         for (row_type r = 0; r < tabular.nrows(); ++r) {
3338                 int maxasc = 0;
3339                 int maxdes = 0;
3340                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3341                         if (tabular.isPartOfMultiColumn(r, c)
3342                                 || tabular.isPartOfMultiRow(r, c))
3343                                 // multicolumn or multirow cell, but not first one
3344                                 continue;
3345                         idx_type const cell = tabular.cellIndex(r, c);
3346                         Dimension dim;
3347                         MetricsInfo m = mi;
3348                         Length const p_width = tabular.getPWidth(cell);
3349                         if (!p_width.zero())
3350                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3351                         tabular.cellInset(cell)->metrics(m, dim);
3352                         if (!p_width.zero())
3353                                 dim.wid = m.base.textwidth;
3354                         tabular.cellInfo(cell).width = dim.wid + 2 * WIDTH_OF_LINE 
3355                                 + tabular.interColumnSpace(cell);
3356
3357                         // FIXME(?): do we need a second metrics call?
3358                         TextMetrics const & tm = 
3359                                 mi.base.bv->textMetrics(tabular.cellInset(cell)->getText(0));
3360
3361                         // determine horiz offset because of decimal align (if necessary)
3362                         int decimal_hoffset = 0;
3363                         int decimal_width = 0;
3364                         if (tabular.getAlignment(cell) == LYX_ALIGN_DECIMAL) {
3365                                 // make a copy which we will split in 2
3366                                 InsetTableCell head = InsetTableCell(*tabular.cellInset(cell).get());
3367                                 head.getText(0)->setMacrocontextPosition(
3368                                         tabular.cellInset(cell)->getText(0)->macrocontextPosition());
3369                                 head.setBuffer(tabular.buffer());
3370                                 // split in 2 and calculate width of each part
3371                                 bool hassep = false;
3372                                 InsetTableCell tail = 
3373                                         splitCell(head, tabular.column_info[c].decimal_point, hassep);
3374                                 Dimension dim1;
3375                                 head.metrics(m, dim1);
3376                                 decimal_hoffset = dim1.width();
3377                                 if (hassep) {
3378                                         tail.metrics(m, dim1);
3379                                         decimal_width = dim1.width();
3380                                 }
3381                         }
3382                         tabular.cell_info[r][c].decimal_hoffset = decimal_hoffset;
3383                         tabular.cell_info[r][c].decimal_width = decimal_width;
3384
3385                         // with LYX_VALIGN_BOTTOM the descent is relative to the last par
3386                         // = descent of text in last par + TEXT_TO_INSET_OFFSET:
3387                         int const lastpardes = tm.last().second->descent()
3388                                 + TEXT_TO_INSET_OFFSET;
3389                         int offset = 0;
3390                         switch (tabular.getVAlignment(cell)) { 
3391                                 case Tabular::LYX_VALIGN_TOP:
3392                                         break; 
3393                                 case Tabular::LYX_VALIGN_MIDDLE:
3394                                         offset = -(dim.des - lastpardes)/2; 
3395                                         break; 
3396                                 case Tabular::LYX_VALIGN_BOTTOM:
3397                                         offset = -(dim.des - lastpardes); 
3398                                         break;
3399                         }
3400                         tabular.cell_info[r][c].voffset = offset;
3401                         maxasc = max(maxasc, dim.asc - offset);
3402                         maxdes = max(maxdes, dim.des + offset);
3403                 }
3404                 int const top_space = tabular.row_info[r].top_space_default ?
3405                         default_line_space :
3406                         tabular.row_info[r].top_space.inPixels(mi.base.textwidth);
3407                 tabular.setRowAscent(r, maxasc + ADD_TO_HEIGHT + top_space);
3408                 int const bottom_space = tabular.row_info[r].bottom_space_default ?
3409                         default_line_space :
3410                         tabular.row_info[r].bottom_space.inPixels(mi.base.textwidth);
3411                 tabular.setRowDescent(r, maxdes + ADD_TO_HEIGHT + bottom_space);
3412         }
3413         tabular.updateColumnWidths();
3414         dim.asc = tabular.rowAscent(0);
3415         dim.des = tabular.height() - dim.asc;
3416         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3417 }
3418
3419
3420 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3421         const
3422 {
3423         if (&cur.inset() == this && cur.selection()) {
3424                 if (cur.selIsMultiCell()) {
3425                         row_type rs, re;
3426                         col_type cs, ce;
3427                         getSelection(cur, rs, re, cs, ce);
3428                         
3429                         idx_type const cell = tabular.cellIndex(row, col);
3430                         col_type const cspan = tabular.columnSpan(cell);
3431                         row_type const rspan = tabular.rowSpan(cell);
3432                         if (col + cspan - 1 >= cs && col <= ce 
3433                                 && row + rspan - 1 >= rs && row <= re)
3434                                 return true;
3435                 } else 
3436                         if (col == tabular.cellColumn(cur.idx()) 
3437                                 && row == tabular.cellRow(cur.idx())) {
3438                         CursorSlice const & beg = cur.selBegin();
3439                         CursorSlice const & end = cur.selEnd();
3440
3441                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3442                                   && end.pos() == end.lastpos() && beg.pos() == 0
3443                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3444                                 return true;
3445                 }
3446         }
3447         return false;
3448 }
3449
3450
3451 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3452 {
3453         x += scx_ + ADD_TO_TABULAR_WIDTH;
3454
3455         BufferView * bv = pi.base.bv;
3456         Cursor & cur = pi.base.bv->cursor();
3457         resetPos(cur);
3458
3459         // FIXME: As the full background is painted in drawSelection(),
3460         // we have no choice but to do a full repaint for the Text cells.
3461         pi.full_repaint = true;
3462
3463         bool const original_selection_state = pi.selected;
3464
3465         idx_type idx = 0;
3466         first_visible_cell = Tabular::npos;
3467         for (row_type r = 0; r < tabular.nrows(); ++r) {
3468                 int nx = x;
3469                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3470                         if (tabular.isPartOfMultiColumn(r, c))
3471                                 continue;
3472                         
3473                         idx = tabular.cellIndex(r, c);
3474                         
3475                         if (tabular.isPartOfMultiRow(r, c)) {
3476                                 nx += tabular.cellWidth(idx);
3477                                 continue;
3478                         }
3479
3480                         if (first_visible_cell == Tabular::npos)
3481                                 first_visible_cell = idx;
3482
3483                         pi.selected |= isCellSelected(cur, r, c);
3484                         int const cx = nx + tabular.textHOffset(idx);
3485                         int const cy = y  + tabular.textVOffset(idx);
3486                         // Cache the Inset position.
3487                         bv->coordCache().insets().add(cell(idx).get(), cx, cy);
3488                         cell(idx)->draw(pi, cx, cy);
3489                         drawCellLines(pi, nx, y, r, idx);
3490                         nx += tabular.cellWidth(idx);
3491                         pi.selected = original_selection_state;
3492                 }
3493
3494                 if (r + 1 < tabular.nrows())
3495                         y += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
3496                                 + tabular.interRowSpace(r + 1);
3497         }
3498 }
3499
3500
3501 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3502 {
3503         Cursor & cur = pi.base.bv->cursor();
3504         resetPos(cur);
3505
3506         x += scx_ + ADD_TO_TABULAR_WIDTH;
3507
3508         // FIXME: it is wrong to completely paint the background
3509         // if we want to do single row painting.
3510
3511         // Paint background of current tabular
3512         int const w = tabular.width();
3513         int const h = tabular.height();
3514         int yy = y - tabular.rowAscent(0);
3515         pi.pain.fillRectangle(x, yy, w, h, pi.backgroundColor(this));
3516
3517         if (!cur.selection())
3518                 return;
3519         if (&cur.inset() != this)
3520                 return;
3521
3522         //resetPos(cur);
3523
3524         bool const full_cell_selected = isCellSelected(cur,
3525                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3526
3527         if (cur.selIsMultiCell() || full_cell_selected) {
3528                 for (row_type r = 0; r < tabular.nrows(); ++r) {
3529                         int xx = x;
3530                         for (col_type c = 0; c < tabular.ncols(); ++c) {
3531                                 if (tabular.isPartOfMultiColumn(r, c))
3532                                         continue;
3533
3534                                 idx_type const cell = tabular.cellIndex(r, c);
3535
3536                                 if (tabular.isPartOfMultiRow(r, c)) {
3537                                         xx += tabular.cellWidth(cell);
3538                                         continue;
3539                                 }
3540                                 int const w = tabular.cellWidth(cell);
3541                                 int const h = tabular.cellHeight(cell);
3542                                 int const yy = y - tabular.rowAscent(r);
3543                                 if (isCellSelected(cur, r, c))
3544                                         pi.pain.fillRectangle(xx, yy, w, h, Color_selection);
3545                                 xx += w;
3546                         }
3547                         if (r + 1 < tabular.nrows())
3548                                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3549                                      + tabular.interRowSpace(r + 1);
3550                 }
3551
3552         } else {
3553                 x += cellXPos(cur.idx());
3554                 x += tabular.textHOffset(cur.idx());
3555                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3556         }
3557 }
3558
3559
3560 void InsetTabular::drawCellLines(PainterInfo & pi, int x, int y,
3561                                  row_type row, idx_type cell) const
3562 {
3563         y -= tabular.rowAscent(row);
3564         int const w = tabular.cellWidth(cell);
3565         int const h = tabular.cellHeight(cell);
3566         Color const linecolor = pi.textColor(Color_tabularline);
3567         Color const gridcolor = pi.textColor(Color_tabularonoffline);
3568
3569         // Top
3570         bool drawline = tabular.topLine(cell)
3571                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
3572         pi.pain.line(x, y, x + w, y,
3573                 drawline ? linecolor : gridcolor,
3574                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3575
3576         // Bottom
3577         drawline = tabular.bottomLine(cell);
3578         pi.pain.line(x, y + h, x + w, y + h,
3579                 drawline ? linecolor : gridcolor,
3580                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3581
3582         // Left
3583         col_type const col = tabular.cellColumn(cell);
3584         drawline = tabular.leftLine(cell)
3585                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
3586         pi.pain.line(x, y, x, y + h,
3587                 drawline ? linecolor : gridcolor,
3588                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3589
3590         // Right
3591         x -= tabular.interColumnSpace(cell);
3592         drawline = tabular.rightLine(cell)
3593                    || (col + 1 < tabular.ncols()
3594                        && tabular.leftLine(tabular.cellIndex(row, col + 1)));
3595         pi.pain.line(x + w, y, x + w, y + h,
3596                 drawline ? linecolor : gridcolor,
3597                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3598 }
3599
3600
3601 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3602 {
3603         //lyxerr << "InsetTabular::edit: " << this << endl;
3604         cur.finishUndo();
3605         cur.setSelection(false);
3606         cur.push(*this);
3607         if (front) {
3608                 if (isRightToLeft(cur))
3609                         cur.idx() = tabular.getLastCellInRow(0);
3610                 else
3611                         cur.idx() = 0;
3612                 cur.pit() = 0;
3613                 cur.pos() = 0;
3614         } else {
3615                 if (isRightToLeft(cur))
3616                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
3617                 else
3618                         cur.idx() = tabular.numberofcells - 1;
3619                 cur.pit() = 0;
3620                 cur.pos() = cur.lastpos(); // FIXME crude guess
3621         }
3622         cur.setCurrentFont();
3623         // FIXME: this accesses the position cache before it is initialized
3624         //resetPos(cur);
3625         //cur.bv().fitCursor();
3626 }
3627
3628
3629 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
3630 {
3631         // In a longtable, tell captions what the current float is
3632         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3633         string const saveflt = cnts.current_float();
3634         if (tabular.is_long_tabular)
3635                 cnts.current_float("table");
3636
3637         ParIterator it2 = it;
3638         it2.forwardPos();
3639         size_t const end = it2.nargs();
3640         for ( ; it2.idx() < end; it2.top().forwardIdx())
3641                 buffer().updateBuffer(it2, utype);
3642
3643         //reset afterwards
3644         if (tabular.is_long_tabular)
3645                 cnts.current_float(saveflt);
3646 }
3647
3648
3649 void InsetTabular::addToToc(DocIterator const & cpit)
3650 {
3651         DocIterator dit = cpit;
3652         dit.forwardPos();
3653         size_t const end = dit.nargs();
3654         for ( ; dit.idx() < end; dit.top().forwardIdx())
3655                 cell(dit.idx())->addToToc(dit);
3656 }
3657
3658
3659 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3660 {
3661         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3662                              << "\n  cur:" << cur);
3663         CursorSlice sl = cur.top();
3664         Cursor & bvcur = cur.bv().cursor();
3665
3666         FuncCode const act = cmd.action();
3667         
3668         switch (act) {
3669
3670         case LFUN_MOUSE_PRESS: {
3671                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3672                 // select row
3673                 if (cmd.x() < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3674                         || cmd.x() > xo(cur.bv()) + tabular.width()) {
3675                         row_type r = rowFromY(cur, cmd.y());
3676                         cur.idx() = tabular.getFirstCellInRow(r);
3677                         cur.pos() = 0;
3678                         cur.resetAnchor();
3679                         cur.idx() = tabular.getLastCellInRow(r);
3680                         cur.pos() = cur.lastpos();
3681                         cur.setSelection(true);
3682                         bvcur = cur; 
3683                         rowselect_ = true;
3684                         break;
3685                 }
3686                 // select column
3687                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3688                 if (cmd.y() < y0 + ADD_TO_TABULAR_WIDTH 
3689                         || cmd.y() > y0 + tabular.height()) {
3690                         col_type c = columnFromX(cur, cmd.x());
3691                         cur.idx() = tabular.cellIndex(0, c);
3692                         cur.pos() = 0;
3693                         cur.resetAnchor();
3694                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3695                         cur.pos() = cur.lastpos();
3696                         cur.setSelection(true);
3697                         bvcur = cur; 
3698                         colselect_ = true;
3699                         break;
3700                 }
3701                 // do not reset cursor/selection if we have selected
3702                 // some cells (bug 2715).
3703                 if (cmd.button() == mouse_button::button3
3704                     && &bvcur.selBegin().inset() == this 
3705                     && bvcur.selIsMultiCell()) 
3706                         ;
3707                 else
3708                         // Let InsetTableCell do it
3709                         cell(cur.idx())->dispatch(cur, cmd);
3710                 break;
3711         }
3712         case LFUN_MOUSE_MOTION:
3713                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3714                 if (cmd.button() == mouse_button::button1) {
3715                         // only accept motions to places not deeper nested than the real anchor
3716                         if (!bvcur.realAnchor().hasPart(cur)) {
3717                                 cur.undispatched();
3718                                 break;
3719                         }
3720                         // select (additional) row
3721                         if (rowselect_) {
3722                                 row_type r = rowFromY(cur, cmd.y());
3723                                 cur.idx() = tabular.getLastCellInRow(r);
3724                                 // we need to reset the cursor's pit and pos now, as the old ones
3725                                 // may no longer be valid.
3726                                 cur.pit() = 0;
3727                                 cur.pos() = 0;
3728                                 bvcur.setCursor(cur);
3729                                 bvcur.setSelection(true);
3730                                 break;
3731                         }
3732                         // select (additional) column
3733                         if (colselect_) {
3734                                 col_type c = columnFromX(cur, cmd.x());
3735                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3736                                 // we need to reset the cursor's pit and pos now, as the old ones
3737                                 // may no longer be valid.
3738                                 cur.pit() = 0;
3739                                 cur.pos() = 0;
3740                                 bvcur.setCursor(cur);
3741                                 bvcur.setSelection(true);
3742                                 break;
3743                         }
3744                         // only update if selection changes
3745                         if (bvcur.idx() == cur.idx() &&
3746                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
3747                                 cur.noScreenUpdate();
3748                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
3749                         bvcur.setCursor(cur);
3750                         bvcur.setSelection(true);
3751                         // if this is a multicell selection, we just set the cursor to
3752                         // the beginning of the cell's text.
3753                         if (bvcur.selIsMultiCell()) {
3754                                 bvcur.pit() = bvcur.lastpit();
3755                                 bvcur.pos() = bvcur.lastpos();
3756                         }
3757                 }
3758                 break;
3759
3760         case LFUN_MOUSE_RELEASE:
3761                 rowselect_ = false;
3762                 colselect_ = false;
3763                 break;
3764
3765         case LFUN_CELL_BACKWARD:
3766                 movePrevCell(cur);
3767                 cur.setSelection(false);
3768                 break;
3769
3770         case LFUN_CELL_FORWARD:
3771                 moveNextCell(cur);
3772                 cur.setSelection(false);
3773                 break;
3774
3775         case LFUN_CHAR_FORWARD_SELECT:
3776         case LFUN_CHAR_FORWARD:
3777         case LFUN_CHAR_BACKWARD_SELECT:
3778         case LFUN_CHAR_BACKWARD:
3779         case LFUN_CHAR_RIGHT_SELECT:
3780         case LFUN_CHAR_RIGHT:
3781         case LFUN_CHAR_LEFT_SELECT:
3782         case LFUN_CHAR_LEFT: 
3783         case LFUN_WORD_FORWARD:
3784         case LFUN_WORD_FORWARD_SELECT:
3785         case LFUN_WORD_BACKWARD:
3786         case LFUN_WORD_BACKWARD_SELECT:
3787         case LFUN_WORD_RIGHT:
3788         case LFUN_WORD_RIGHT_SELECT:
3789         case LFUN_WORD_LEFT:
3790         case LFUN_WORD_LEFT_SELECT: {
3791                 // determine whether we move to next or previous cell, where to enter 
3792                 // the new cell from, and which command to "finish" (i.e., exit the
3793                 // inset) with:
3794                 bool next_cell;
3795                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3796                 FuncCode finish_lfun;
3797
3798                 if (act == LFUN_CHAR_FORWARD 
3799                                 || act == LFUN_CHAR_FORWARD_SELECT
3800                                 || act == LFUN_WORD_FORWARD
3801                                 || act == LFUN_WORD_FORWARD_SELECT) {
3802                         next_cell = true;
3803                         finish_lfun = LFUN_FINISHED_FORWARD;
3804                 }
3805                 else if (act == LFUN_CHAR_BACKWARD
3806                                 || act == LFUN_CHAR_BACKWARD_SELECT
3807                                 || act == LFUN_WORD_BACKWARD
3808                                 || act == LFUN_WORD_BACKWARD_SELECT) {
3809                         next_cell = false;
3810                         finish_lfun = LFUN_FINISHED_BACKWARD;
3811                 }
3812                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3813                 // table's direction.
3814                 else {
3815                         bool const right = act == LFUN_CHAR_RIGHT
3816                                 || act == LFUN_CHAR_RIGHT_SELECT
3817                                 || act == LFUN_WORD_RIGHT
3818                                 || act == LFUN_WORD_RIGHT_SELECT;
3819                         next_cell = isRightToLeft(cur) != right;
3820                         
3821                         if (lyxrc.visual_cursor)
3822                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3823
3824                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
3825                 }
3826
3827                 bool const select =     act == LFUN_CHAR_FORWARD_SELECT 
3828                     || act == LFUN_CHAR_BACKWARD_SELECT
3829                     || act == LFUN_CHAR_RIGHT_SELECT
3830                     || act == LFUN_CHAR_LEFT_SELECT
3831                         || act == LFUN_WORD_FORWARD_SELECT
3832                         || act == LFUN_WORD_RIGHT_SELECT
3833                         || act == LFUN_WORD_BACKWARD_SELECT
3834                         || act == LFUN_WORD_LEFT_SELECT;
3835
3836                 // If we have a multicell selection or we're 
3837                 // not doing some LFUN_*_SELECT thing anyway...
3838                 if (!cur.selIsMultiCell() || !select) {
3839                         col_type const c = tabular.cellColumn(cur.idx());
3840                         row_type const r = tabular.cellRow(cur.idx());
3841                         // Are we trying to select the whole cell and is the whole cell 
3842                         // not yet selected?
3843                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
3844                                 ((next_cell && cur.pit() == cur.lastpit() 
3845                                 && cur.pos() == cur.lastpos())
3846                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
3847
3848                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
3849
3850                         // ...try to dispatch to the cell's inset.
3851                         cell(cur.idx())->dispatch(cur, cmd);
3852
3853                         // When we already have a selection we want to select the whole cell
3854                         // before going to the next cell.
3855                         if (select_whole && !empty_cell){
3856                                 getText(cur.idx())->selectAll(cur);
3857                                 cur.dispatched();
3858                                 break;
3859                         }
3860
3861                         // FIXME: When we support the selection of an empty cell, remove 
3862                         // the !empty_cell from this condition. For now we jump to the next
3863                         // cell if the current cell is empty.
3864                         if (cur.result().dispatched() && !empty_cell)
3865                                 break;
3866                 }
3867
3868                 // move to next/prev cell, as appropriate
3869                 // note that we will always do this if we're selecting and we have
3870                 // a multicell selection
3871                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3872                         << " cell from: " << int(entry_from));
3873                 if (next_cell)
3874                         moveNextCell(cur, entry_from);
3875                 else
3876                         movePrevCell(cur, entry_from);
3877                 // if we're exiting the table, call the appropriate FINISHED lfun
3878                 if (sl == cur.top())
3879                         cmd = FuncRequest(finish_lfun);
3880                 else
3881                         cur.dispatched();
3882                 break;
3883
3884         }
3885
3886         case LFUN_DOWN_SELECT:
3887         case LFUN_DOWN:
3888                 if (!(cur.selection() && cur.selIsMultiCell()))
3889                         cell(cur.idx())->dispatch(cur, cmd);
3890                 
3891                 cur.dispatched(); // override the cell's decision
3892                 if (sl == cur.top()) {
3893                         // if our Text didn't do anything to the cursor
3894                         // then we try to put the cursor into the cell below
3895                         // setting also the right targetX.
3896                         cur.selHandle(act == LFUN_DOWN_SELECT);
3897                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
3898                                 cur.idx() = tabular.cellBelow(cur.idx());
3899                                 cur.pit() = 0;
3900                                 TextMetrics const & tm =
3901                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3902                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3903                                 cur.setCurrentFont();
3904                         }
3905                 }
3906                 if (sl == cur.top()) {
3907                         // we trick it to go to forward after leaving the
3908                         // tabular.
3909                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3910                         cur.undispatched();
3911                 }
3912                 if (cur.selIsMultiCell()) {
3913                         cur.pit() = cur.lastpit();
3914                         cur.pos() = cur.lastpos();
3915                         cur.setCurrentFont();
3916                         return;
3917                 }
3918                 break;
3919
3920         case LFUN_UP_SELECT:
3921         case LFUN_UP:
3922                 if (!(cur.selection() && cur.selIsMultiCell()))
3923                         cell(cur.idx())->dispatch(cur, cmd);
3924                 cur.dispatched(); // override the cell's decision
3925                 if (sl == cur.top()) {
3926                         // if our Text didn't do anything to the cursor
3927                         // then we try to put the cursor into the cell above
3928                         // setting also the right targetX.
3929                         cur.selHandle(act == LFUN_UP_SELECT);
3930                         if (tabular.cellRow(cur.idx()) != 0) {
3931                                 cur.idx() = tabular.cellAbove(cur.idx());
3932                                 cur.pit() = cur.lastpit();
3933                                 Text const * text = cell(cur.idx())->getText(0);
3934                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3935                                 ParagraphMetrics const & pm =
3936                                         tm.parMetrics(cur.lastpit());
3937                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3938                                 cur.setCurrentFont();
3939                         }
3940                 }
3941                 if (sl == cur.top()) {
3942                         cmd = FuncRequest(LFUN_UP);
3943                         cur.undispatched();
3944                 }
3945                 if (cur.selIsMultiCell()) {
3946                         cur.pit() = 0;
3947                         cur.pos() = cur.lastpos();
3948                         cur.setCurrentFont();
3949                         return;
3950                 }
3951                 break;
3952
3953 //      case LFUN_SCREEN_DOWN: {
3954 //              //if (hasSelection())
3955 //              //      cur.selection() = false;
3956 //              col_type const col = tabular.cellColumn(cur.idx());
3957 //              int const t =   cur.bv().top_y() + cur.bv().height();
3958 //              if (t < yo() + tabular.getHeightOfTabular()) {
3959 //                      cur.bv().scrollDocView(t, true);
3960 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3961 //              } else {
3962 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3963 //              }
3964 //              cur.par() = 0;
3965 //              cur.pos() = 0;
3966 //              break;
3967 //      }
3968 //
3969 //      case LFUN_SCREEN_UP: {
3970 //              //if (hasSelection())
3971 //              //      cur.selection() = false;
3972 //              col_type const col = tabular.cellColumn(cur.idx());
3973 //              int const t =   cur.bv().top_y() + cur.bv().height();
3974 //              if (yo() < 0) {
3975 //                      cur.bv().scrollDocView(t, true);
3976 //                      if (yo() > 0)
3977 //                              cur.idx() = col;
3978 //                      else
3979 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3980 //              } else {
3981 //                      cur.idx() = col;
3982 //              }
3983 //              cur.par() = cur.lastpar();
3984 //              cur.pos() = cur.lastpos();
3985 //              break;
3986 //      }
3987
3988         case LFUN_LAYOUT_TABULAR:
3989                 cur.bv().showDialog("tabular");
3990                 break;
3991
3992         case LFUN_INSET_MODIFY:
3993                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3994                         cur.undispatched();
3995                 break;
3996
3997         // insert file functions
3998         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3999         case LFUN_FILE_INSERT_PLAINTEXT:
4000                 // FIXME UNICODE
4001                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
4002                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
4003                                 FileName(to_utf8(cmd.argument())));
4004                         if (tmpstr.empty())
4005                                 break;
4006                         cur.recordUndoInset(INSERT_UNDO);
4007                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
4008                                 // content has been replaced,
4009                                 // so cursor might be invalid
4010                                 cur.pos() = cur.lastpos();
4011                                 cur.pit() = cur.lastpit();
4012                                 bvcur.setCursor(cur);
4013                         } else
4014                                 cur.undispatched();
4015                 }
4016                 break;
4017
4018         case LFUN_CUT:
4019                 if (cur.selIsMultiCell()) {
4020                         if (copySelection(cur)) {
4021                                 cur.recordUndoInset(DELETE_UNDO);
4022                                 cutSelection(cur);
4023                         }
4024                 } else
4025                         cell(cur.idx())->dispatch(cur, cmd);
4026                 break;
4027
4028         case LFUN_SELF_INSERT:
4029                 if (cur.selIsMultiCell()) {
4030                         cur.recordUndoInset(DELETE_UNDO);
4031                         cutSelection(cur);
4032                 }
4033                 cell(cur.idx())->dispatch(cur, cmd);
4034                 break;
4035
4036         case LFUN_CHAR_DELETE_BACKWARD:
4037         case LFUN_CHAR_DELETE_FORWARD:
4038                 if (cur.selIsMultiCell()) {
4039                         cur.recordUndoInset(DELETE_UNDO);
4040                         cutSelection(cur);
4041                 } else
4042                         cell(cur.idx())->dispatch(cur, cmd);
4043                 break;
4044
4045         case LFUN_COPY:
4046                 if (!cur.selection())
4047                         break;
4048                 if (cur.selIsMultiCell()) {
4049                         cur.finishUndo();
4050                         copySelection(cur);
4051                 } else
4052                         cell(cur.idx())->dispatch(cur, cmd);
4053                 break;
4054
4055         case LFUN_CLIPBOARD_PASTE:
4056         case LFUN_PRIMARY_SELECTION_PASTE: {
4057                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
4058                         theClipboard().getAsText() :
4059                         theSelection().get();
4060                 if (clip.empty())
4061                         break;
4062                 // pass to InsertPlaintextString, but
4063                 // only if we have multi-cell content
4064                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
4065                         cur.recordUndoInset(INSERT_UNDO);
4066                         if (insertPlaintextString(cur.bv(), clip, false)) {
4067                                 // content has been replaced,
4068                                 // so cursor might be invalid
4069                                 cur.pos() = cur.lastpos();
4070                                 cur.pit() = cur.lastpit();
4071                                 bvcur.setCursor(cur);
4072                                 break;
4073                         }
4074                 }
4075                 // Let the cell handle normal text
4076                 cell(cur.idx())->dispatch(cur, cmd);
4077                 break;
4078         }
4079
4080         case LFUN_PASTE:
4081                 if (!tabularStackDirty()) {
4082                         if (!cur.selIsMultiCell())
4083                                 cell(cur.idx())->dispatch(cur, cmd);
4084                         break;
4085                 }
4086                 if (theClipboard().isInternal() ||
4087                     (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
4088                         cur.recordUndoInset(INSERT_UNDO);
4089                         pasteClipboard(cur);
4090                 }
4091                 break;
4092
4093         case LFUN_FONT_EMPH:
4094         case LFUN_FONT_BOLD:
4095         case LFUN_FONT_BOLDSYMBOL:
4096         case LFUN_FONT_ROMAN:
4097         case LFUN_FONT_NOUN:
4098         case LFUN_FONT_ITAL:
4099         case LFUN_FONT_FRAK:
4100         case LFUN_FONT_TYPEWRITER:
4101         case LFUN_FONT_SANS:
4102         case LFUN_TEXTSTYLE_APPLY:
4103         case LFUN_TEXTSTYLE_UPDATE:
4104         case LFUN_FONT_SIZE:
4105         case LFUN_FONT_UNDERLINE:
4106         case LFUN_FONT_STRIKEOUT:
4107         case LFUN_FONT_UULINE:
4108         case LFUN_FONT_UWAVE:
4109         case LFUN_LANGUAGE:
4110         case LFUN_WORD_CAPITALIZE:
4111         case LFUN_WORD_UPCASE:
4112         case LFUN_WORD_LOWCASE:
4113         case LFUN_CHARS_TRANSPOSE:
4114                 if (cur.selIsMultiCell()) {
4115                         row_type rs, re;
4116                         col_type cs, ce;
4117                         getSelection(cur, rs, re, cs, ce);
4118                         Cursor tmpcur = cur;
4119                         for (row_type r = rs; r <= re; ++r) {
4120                                 for (col_type c = cs; c <= ce; ++c) {
4121                                         // cursor follows cell:
4122                                         tmpcur.idx() = tabular.cellIndex(r, c);
4123                                         // select this cell only:
4124                                         tmpcur.pit() = 0;
4125                                         tmpcur.pos() = 0;
4126                                         tmpcur.resetAnchor();
4127                                         tmpcur.pit() = tmpcur.lastpit();
4128                                         tmpcur.pos() = tmpcur.top().lastpos();
4129                                         tmpcur.setCursor(tmpcur);
4130                                         tmpcur.setSelection();
4131                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
4132                                 }
4133                         }
4134                         break;
4135                 } else {
4136                         cell(cur.idx())->dispatch(cur, cmd);
4137                         break;
4138                 }
4139
4140         case LFUN_INSET_SETTINGS:
4141                 // relay this lfun to Inset, not to the cell.
4142                 Inset::doDispatch(cur, cmd);
4143                 break;
4144
4145         default:
4146                 // we try to handle this event in the insets dispatch function.
4147                 cell(cur.idx())->dispatch(cur, cmd);
4148                 break;
4149         }
4150 }
4151
4152
4153 // function sets an object as defined in func_status.h:
4154 // states OK, Unknown, Disabled, On, Off.
4155 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
4156         FuncStatus & status) const
4157 {
4158         switch (cmd.action()) {
4159         case LFUN_INSET_MODIFY: {
4160                 if (&cur.inset() != this || cmd.getArg(0) != "tabular") 
4161                         break;
4162
4163                 string const s = cmd.getArg(1);
4164                 // FIXME: We only check for the very first argument...
4165                 int action = Tabular::LAST_ACTION;
4166                 int i = 0;
4167                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4168                         if (tabularFeature[i].feature == s) {
4169                                 action = tabularFeature[i].action;
4170                                 break;
4171                         }
4172                 }
4173                 if (action == Tabular::LAST_ACTION) {
4174                         status.clear();
4175                         status.setUnknown(true);
4176                         return true;
4177                 }
4178
4179                 string const argument = cmd.getLongArg(2);
4180
4181                 row_type sel_row_start = 0;
4182                 row_type sel_row_end = 0;
4183                 col_type sel_col_start = 0;
4184                 col_type sel_col_end = 0;
4185                 Tabular::ltType dummyltt;
4186                 bool flag = true;
4187
4188                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4189
4190                 switch (action) {
4191                 case Tabular::SET_PWIDTH:
4192                 case Tabular::SET_MPWIDTH:
4193                 case Tabular::SET_SPECIAL_COLUMN:
4194                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4195                 case Tabular::APPEND_ROW:
4196                 case Tabular::APPEND_COLUMN:
4197                 case Tabular::DELETE_ROW:
4198                 case Tabular::DELETE_COLUMN:
4199                 case Tabular::COPY_ROW:
4200                 case Tabular::COPY_COLUMN:
4201                 case Tabular::SET_TOP_SPACE:
4202                 case Tabular::SET_BOTTOM_SPACE:
4203                 case Tabular::SET_INTERLINE_SPACE:
4204                         status.clear();
4205                         return true;
4206
4207                 case Tabular::SET_DECIMAL_POINT:
4208                         status.setEnabled(
4209                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
4210                         break;
4211
4212                 case Tabular::SET_MULTICOLUMN:
4213                 case Tabular::UNSET_MULTICOLUMN:
4214                 case Tabular::MULTICOLUMN:
4215                         // If a row is set as longtable caption, it must not be allowed
4216                         // to unset that this row is a multicolumn.
4217                         status.setEnabled(sel_row_start == sel_row_end
4218                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4219                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4220                         break;
4221
4222                 case Tabular::SET_MULTIROW:
4223                 case Tabular::UNSET_MULTIROW:
4224                 case Tabular::MULTIROW:
4225                         // If a row is set as longtable caption, it must not be allowed
4226                         // to unset that this row is a multirow.
4227                         status.setEnabled(sel_col_start == sel_col_end
4228                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4229                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4230                         break;
4231
4232                 case Tabular::SET_ALL_LINES:
4233                 case Tabular::UNSET_ALL_LINES:
4234                 case Tabular::SET_BORDER_LINES:
4235                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4236                         break;
4237
4238                 case Tabular::SET_LINE_TOP:
4239                 case Tabular::SET_LINE_BOTTOM:
4240                 case Tabular::SET_LINE_LEFT:
4241                 case Tabular::SET_LINE_RIGHT:
4242                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4243                         break;
4244
4245                 case Tabular::TOGGLE_LINE_TOP:
4246                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4247                         status.setOnOff(tabular.topLine(cur.idx()));
4248                         break;
4249
4250                 case Tabular::TOGGLE_LINE_BOTTOM:
4251                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4252                         status.setOnOff(tabular.bottomLine(cur.idx()));
4253                         break;
4254
4255                 case Tabular::TOGGLE_LINE_LEFT:
4256                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4257                         status.setOnOff(tabular.leftLine(cur.idx()));
4258                         break;
4259
4260                 case Tabular::TOGGLE_LINE_RIGHT:
4261                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4262                         status.setOnOff(tabular.rightLine(cur.idx()));
4263                         break;
4264
4265                 case Tabular::M_ALIGN_LEFT:
4266                         flag = false;
4267                 case Tabular::ALIGN_LEFT:
4268                         status.setEnabled(!tabular.isMultiRow(cur.idx()));
4269                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4270                         break;
4271
4272                 case Tabular::M_ALIGN_RIGHT:
4273                         flag = false;
4274                 case Tabular::ALIGN_RIGHT:
4275                         status.setEnabled(!tabular.isMultiRow(cur.idx()));
4276                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4277                         break;
4278
4279                 case Tabular::M_ALIGN_CENTER:
4280                         flag = false;
4281                 case Tabular::ALIGN_CENTER:
4282                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4283                         break;
4284
4285                 case Tabular::ALIGN_BLOCK:
4286                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4287                                 && !tabular.isMultiRow(cur.idx()));
4288                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4289                         break;
4290
4291                 case Tabular::ALIGN_DECIMAL:
4292                         status.setEnabled(!tabular.isMultiRow(cur.idx()) 
4293                                 && !tabular.isMultiColumn(cur.idx()));
4294                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
4295                         break;
4296
4297                 case Tabular::M_VALIGN_TOP:
4298                         flag = false;
4299                 case Tabular::VALIGN_TOP:
4300                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4301                                 && !tabular.isMultiRow(cur.idx()));
4302                         status.setOnOff(
4303                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4304                         break;
4305
4306                 case Tabular::M_VALIGN_BOTTOM:
4307                         flag = false;
4308                 case Tabular::VALIGN_BOTTOM:
4309                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4310                                 && !tabular.isMultiRow(cur.idx()));
4311                         status.setOnOff(
4312                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4313                         break;
4314
4315                 case Tabular::M_VALIGN_MIDDLE:
4316                         flag = false;
4317                 case Tabular::VALIGN_MIDDLE:
4318                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4319                                 && !tabular.isMultiRow(cur.idx()));
4320                         status.setOnOff(
4321                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4322                         break;
4323
4324                 case Tabular::SET_LONGTABULAR:
4325                         // setting as longtable is not allowed when table is inside a float
4326                         if (cur.innerInsetOfType(FLOAT_CODE) != 0
4327                                 || cur.innerInsetOfType(WRAP_CODE) != 0)
4328                                 status.setEnabled(false);
4329                         else
4330                                 status.setEnabled(true);
4331                         status.setOnOff(tabular.is_long_tabular);
4332                         break;
4333
4334                 case Tabular::UNSET_LONGTABULAR:
4335                         status.setOnOff(!tabular.is_long_tabular);
4336                         break;
4337
4338                 case Tabular::TOGGLE_ROTATE_TABULAR:
4339                 case Tabular::SET_ROTATE_TABULAR:
4340                         status.setOnOff(tabular.rotate);
4341                         break;
4342
4343                 case Tabular::TABULAR_VALIGN_TOP:
4344                         status.setOnOff(tabular.tabular_valignment 
4345                                 == Tabular::LYX_VALIGN_TOP);
4346                         break;
4347                 case Tabular::TABULAR_VALIGN_MIDDLE:
4348                         status.setOnOff(tabular.tabular_valignment 
4349                                 == Tabular::LYX_VALIGN_MIDDLE);
4350                         break;
4351                 case Tabular::TABULAR_VALIGN_BOTTOM:
4352                         status.setOnOff(tabular.tabular_valignment 
4353                                 == Tabular::LYX_VALIGN_BOTTOM);
4354                         break;
4355
4356                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4357                         status.setOnOff(tabular.longtabular_alignment 
4358                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4359                         break;
4360                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4361                         status.setOnOff(tabular.longtabular_alignment 
4362                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4363                         break;
4364                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4365                         status.setOnOff(tabular.longtabular_alignment 
4366                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4367                         break;
4368
4369                 case Tabular::UNSET_ROTATE_TABULAR:
4370                         status.setOnOff(!tabular.rotate);
4371                         break;
4372
4373                 case Tabular::TOGGLE_ROTATE_CELL:
4374                 case Tabular::SET_ROTATE_CELL:
4375                         status.setOnOff(!oneCellHasRotationState(false,
4376                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4377                         break;
4378
4379                 case Tabular::UNSET_ROTATE_CELL:
4380                         status.setOnOff(!oneCellHasRotationState(true,
4381                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4382                         break;
4383
4384                 case Tabular::SET_USEBOX:
4385                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4386                         break;
4387
4388                 // every row can only be one thing:
4389                 // either a footer or header or caption
4390                 case Tabular::SET_LTFIRSTHEAD:
4391                         status.setEnabled(sel_row_start == sel_row_end
4392                                 && !tabular.ltCaption(sel_row_start));
4393                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4394                         break;
4395
4396                 case Tabular::UNSET_LTFIRSTHEAD:
4397                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4398                         break;
4399
4400                 case Tabular::SET_LTHEAD:
4401                         status.setEnabled(sel_row_start == sel_row_end
4402                                 && !tabular.ltCaption(sel_row_start));
4403                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4404                         break;
4405
4406                 case Tabular::UNSET_LTHEAD:
4407                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4408                         break;
4409
4410                 case Tabular::SET_LTFOOT:
4411                         status.setEnabled(sel_row_start == sel_row_end
4412                                 && !tabular.ltCaption(sel_row_start));
4413                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4414                         break;
4415
4416                 case Tabular::UNSET_LTFOOT:
4417                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4418                         break;
4419
4420                 case Tabular::SET_LTLASTFOOT:
4421                         status.setEnabled(sel_row_start == sel_row_end
4422                                 && !tabular.ltCaption(sel_row_start));
4423                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4424                         break;
4425
4426                 case Tabular::UNSET_LTLASTFOOT:
4427                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4428                         break;
4429
4430                 case Tabular::SET_LTNEWPAGE:
4431                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4432                         break;
4433
4434                 // only one row can be the caption
4435                 // and a multirow cannot be set as caption
4436                 case Tabular::SET_LTCAPTION:
4437                 case Tabular::UNSET_LTCAPTION:
4438                 case Tabular::TOGGLE_LTCAPTION:
4439                         status.setEnabled(sel_row_start == sel_row_end
4440                                 && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4441                                 && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
4442                                 && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4443                                 && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4444                                 && (!tabular.haveLTCaption()
4445                                         || tabular.ltCaption(sel_row_start))
4446                                 && !tabular.isMultiRow(sel_row_start));
4447                         status.setOnOff(tabular.ltCaption(sel_row_start));
4448                         break;
4449
4450                 case Tabular::SET_BOOKTABS:
4451                         status.setOnOff(tabular.use_booktabs);
4452                         break;
4453
4454                 case Tabular::UNSET_BOOKTABS:
4455                         status.setOnOff(!tabular.use_booktabs);
4456                         break;
4457
4458                 default:
4459                         status.clear();
4460                         status.setEnabled(false);
4461                         break;
4462                 }
4463                 return true;
4464         }
4465
4466         // These are only enabled inside tabular
4467         case LFUN_CELL_BACKWARD:
4468         case LFUN_CELL_FORWARD:
4469                 status.setEnabled(true);
4470                 return true;
4471
4472         // disable these with multiple cells selected
4473         case LFUN_INSET_INSERT:
4474         case LFUN_TABULAR_INSERT:
4475         case LFUN_FLEX_INSERT:
4476         case LFUN_FLOAT_INSERT:
4477         case LFUN_FLOAT_WIDE_INSERT:
4478         case LFUN_FOOTNOTE_INSERT:
4479         case LFUN_MARGINALNOTE_INSERT:
4480         case LFUN_MATH_INSERT:
4481         case LFUN_MATH_MODE:
4482         case LFUN_MATH_MUTATE:
4483         case LFUN_MATH_DISPLAY:
4484         case LFUN_NOTE_INSERT:
4485         case LFUN_ARGUMENT_INSERT:
4486         case LFUN_BOX_INSERT:
4487         case LFUN_BRANCH_INSERT:
4488         case LFUN_PHANTOM_INSERT:
4489         case LFUN_WRAP_INSERT:
4490         case LFUN_PREVIEW_INSERT:
4491         case LFUN_ERT_INSERT: {
4492                 if (cur.selIsMultiCell()) {
4493                         status.setEnabled(false);
4494                         return true;
4495                 } else
4496                         return cell(cur.idx())->getStatus(cur, cmd, status);
4497         }
4498
4499         // disable in non-fixed-width cells
4500         case LFUN_NEWLINE_INSERT:
4501         case LFUN_BREAK_PARAGRAPH: {
4502                 if (tabular.getPWidth(cur.idx()).zero()) {
4503                         status.setEnabled(false);
4504                         return true;
4505                 } else
4506                         return cell(cur.idx())->getStatus(cur, cmd, status);
4507         }
4508
4509         case LFUN_NEWPAGE_INSERT:
4510                 status.setEnabled(false);
4511                 return true;
4512
4513         case LFUN_PASTE:
4514                 if (tabularStackDirty() && theClipboard().isInternal()) {
4515                         if (cur.selIsMultiCell()) {
4516                                 row_type rs, re;
4517                                 col_type cs, ce;
4518                                 getSelection(cur, rs, re, cs, ce);
4519                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
4520                                           && paste_tabular->nrows() == re - rs + 1)
4521                                         status.setEnabled(true);        
4522                                 else {
4523                                         status.setEnabled(false);
4524                                         status.message(_("Selection size should match clipboard content."));
4525                                 }
4526                         } else
4527                                 status.setEnabled(true);
4528                         return true;
4529                 }
4530                 return cell(cur.idx())->getStatus(cur, cmd, status);
4531
4532         case LFUN_INSET_SETTINGS:
4533                 // relay this lfun to Inset, not to the cell.
4534                 return Inset::getStatus(cur, cmd, status);
4535
4536         default:
4537                 // we try to handle this event in the insets dispatch function.
4538                 return cell(cur.idx())->getStatus(cur, cmd, status);
4539         }
4540         return false;
4541 }
4542
4543
4544 Inset::DisplayType InsetTabular::display() const
4545 {
4546                 if (tabular.is_long_tabular) {
4547                         switch (tabular.longtabular_alignment) {
4548                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4549                                 return AlignLeft;
4550                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4551                                 return AlignCenter;
4552                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4553                                 return AlignRight;
4554                         default:
4555                                 return AlignCenter;
4556                         }
4557                 } else
4558                         return Inline;
4559 }
4560
4561
4562 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
4563 {
4564         return tabular.latex(os, runparams);
4565 }
4566
4567
4568 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4569 {
4570         os << '\n'; // output table on a new line
4571         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4572         tabular.plaintext(os, runparams, dp, false, 0);
4573         return PLAINTEXT_NEWLINE;
4574 }
4575
4576
4577 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4578 {
4579         int ret = 0;
4580         Inset * master = 0;
4581
4582         // FIXME: Why not pass a proper DocIterator here?
4583 #if 0
4584         // if the table is inside a float it doesn't need the informaltable
4585         // wrapper. Search for it.
4586         for (master = owner(); master; master = master->owner())
4587                 if (master->lyxCode() == FLOAT_CODE)
4588                         break;
4589 #endif
4590
4591         if (!master) {
4592                 os << "<informaltable>";
4593                 ++ret;
4594         }
4595         ret += tabular.docbook(os, runparams);
4596         if (!master) {
4597                 os << "</informaltable>";
4598                 ++ret;
4599         }
4600         return ret;
4601 }
4602
4603
4604 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
4605 {
4606         // FIXME XHTML
4607         // It'd be better to be able to get this from an InsetLayout, but at present
4608         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
4609         xs << html::StartTag("table");
4610         docstring ret = tabular.xhtml(xs, rp);
4611         xs << html::EndTag("table");
4612         return ret;
4613 }
4614
4615
4616 void InsetTabular::validate(LaTeXFeatures & features) const
4617 {
4618         tabular.validate(features);
4619         // FIXME XHTML
4620         // It'd be better to be able to get this from an InsetLayout, but at present
4621         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
4622         if (features.runparams().flavor == OutputParams::HTML)
4623                 features.addPreambleSnippet("<style type=\"text/css\">\n"
4624       "table { border: 1px solid black; display: inline-block; }\n"
4625       "td { border: 1px solid black; padding: 0.5ex; }\n"
4626       "</style>");
4627 }
4628
4629
4630 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4631 {
4632         return tabular.cellInset(idx);
4633 }
4634
4635
4636 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4637 {
4638         return tabular.cellInset(idx);
4639 }
4640
4641
4642 void InsetTabular::cursorPos(BufferView const & bv,
4643                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4644 {
4645         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4646
4647         int const row = tabular.cellRow(sl.idx());
4648         int const col = tabular.cellColumn(sl.idx());
4649
4650         // y offset     correction
4651         for (int r = 0; r < row; ++r)
4652                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
4653                         + tabular.interRowSpace(r + 1);
4654
4655         y += tabular.textVOffset(sl.idx());
4656
4657         // x offset correction
4658         for (int c = 0; c < col; ++c)
4659                 x += tabular.column_info[c].width;
4660         
4661         x += tabular.textHOffset(sl.idx());
4662         x += ADD_TO_TABULAR_WIDTH;
4663         x += scx_;
4664 }
4665
4666
4667 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4668 {
4669         int xx = 0;
4670         int yy = 0;
4671         Inset const & inset = *tabular.cellInset(cell);
4672         Point o = bv.coordCache().getInsets().xy(&inset);
4673         int const xbeg = o.x_ - tabular.textHOffset(cell);
4674         int const xend = xbeg + tabular.cellWidth(cell);
4675         row_type const row = tabular.cellRow(cell);
4676         int const ybeg = o.y_ - tabular.rowAscent(row)
4677                 - tabular.interRowSpace(row);
4678         int const yend = ybeg + tabular.cellHeight(cell);
4679
4680         if (x < xbeg)
4681                 xx = xbeg - x;
4682         else if (x > xend)
4683                 xx = x - xend;
4684
4685         if (y < ybeg)
4686                 yy = ybeg - y;
4687         else if (y > yend)
4688                 yy = y - yend;
4689
4690         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4691         //       << " ybeg=" << ybeg << " yend=" << yend
4692         //       << " xx=" << xx << " yy=" << yy
4693         //       << " dist=" << xx + yy << endl;
4694         return xx + yy;
4695 }
4696
4697
4698 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4699 {
4700         //lyxerr << "InsetTabular::editXY: " << this << endl;
4701         cur.setSelection(false);
4702         cur.push(*this);
4703         cur.idx() = getNearestCell(cur.bv(), x, y);
4704         resetPos(cur);
4705         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4706 }
4707
4708
4709 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4710 {
4711         cur.idx() = getNearestCell(cur.bv(), x, y);
4712         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4713 }
4714
4715
4716 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4717 {
4718         idx_type idx_min = 0;
4719         int dist_min = numeric_limits<int>::max();
4720         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4721                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4722                         int const d = dist(bv, i, x, y);
4723                         if (d < dist_min) {
4724                                 dist_min = d;
4725                                 idx_min = i;
4726                         }
4727                 }
4728         }
4729         return idx_min;
4730 }
4731
4732
4733 int InsetTabular::cellXPos(idx_type const cell) const
4734 {
4735         col_type col = tabular.cellColumn(cell);
4736         int lx = 0;
4737         for (col_type c = 0; c < col; ++c)
4738                 lx += tabular.column_info[c].width;
4739
4740         return lx;
4741 }
4742
4743
4744 void InsetTabular::resetPos(Cursor & cur) const
4745 {
4746         BufferView & bv = cur.bv();
4747         int const maxwidth = bv.workWidth();
4748
4749         int const scx_old = scx_;
4750         int const i = cur.find(this);
4751         if (i == -1) {
4752                 scx_ = 0;
4753         } else {
4754                 int const X1 = 0;
4755                 int const X2 = maxwidth;
4756                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4757                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4758                 int const x2 = x1 + tabular.cellWidth(cur[i].idx());
4759
4760                 if (x1 < X1)
4761                         scx_ = X1 + 20 - x1;
4762                 else if (x2 > X2)
4763                         scx_ = X2 - 20 - x2;
4764                 else
4765                         scx_ = 0;
4766         }
4767
4768         // only update if offset changed
4769         if (scx_ != scx_old)
4770                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4771 }
4772
4773
4774 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4775 {
4776         row_type const row = tabular.cellRow(cur.idx());
4777         col_type const col = tabular.cellColumn(cur.idx());
4778
4779         if (isRightToLeft(cur)) {
4780                 if (tabular.cellColumn(cur.idx()) == 0) {
4781                         if (row == tabular.nrows() - 1)
4782                                 return;
4783                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4784                 } else {
4785                         if (cur.idx() == 0)
4786                                 return;
4787                         if (col == 0)
4788                                 cur.idx() = tabular.getLastCellInRow(row - 1);
4789                         else
4790                                 cur.idx() = tabular.cellIndex(row, col - 1);
4791                 }
4792         } else {
4793                 if (tabular.isLastCell(cur.idx()))
4794                         return;
4795                 if (cur.idx() == tabular.getLastCellInRow(row))
4796                         cur.idx() = tabular.cellIndex(row + 1, 0);
4797                 else {
4798                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
4799                         cur.idx() = tabular.cellIndex(row, colnextcell);
4800                 }
4801         }
4802
4803         cur.boundary(false);
4804
4805         if (cur.selIsMultiCell()) {
4806                 cur.pit() = cur.lastpit();
4807                 cur.pos() = cur.lastpos();
4808                 resetPos(cur);
4809                 return;
4810         }
4811
4812         cur.pit() = 0;
4813         cur.pos() = 0;
4814
4815         // in visual mode, place cursor at extreme left or right
4816         
4817         switch(entry_from) {
4818
4819         case ENTRY_DIRECTION_RIGHT:
4820                 cur.posVisToRowExtremity(false /* !left */);
4821                 break;
4822         case ENTRY_DIRECTION_LEFT:
4823                 cur.posVisToRowExtremity(true /* left */);
4824                 break;
4825         case ENTRY_DIRECTION_IGNORE:
4826                 // nothing to do in this case
4827                 break;
4828
4829         }
4830         cur.setCurrentFont();
4831         resetPos(cur);
4832 }
4833
4834
4835 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4836 {
4837         row_type const row = tabular.cellRow(cur.idx());
4838         col_type const col = tabular.cellColumn(cur.idx());
4839
4840         if (isRightToLeft(cur)) {
4841                 if (cur.idx() == tabular.getLastCellInRow(row)) {
4842                         if (row == 0)
4843                                 return;
4844                         cur.idx() = tabular.getFirstCellInRow(row);
4845                         cur.idx() = tabular.cellAbove(cur.idx());
4846                 } else {
4847                         if (tabular.isLastCell(cur.idx()))
4848                                 return;
4849                         if (cur.idx() == tabular.getLastCellInRow(row))
4850                                 cur.idx() = tabular.cellIndex(row + 1, 0);
4851                         else
4852                                 cur.idx() = tabular.cellIndex(row, col + 1);
4853                 }
4854         } else {
4855                 if (cur.idx() == 0) // first cell
4856                         return;
4857                 if (col == 0)
4858                         cur.idx() = tabular.getLastCellInRow(row - 1);
4859                 else
4860                         cur.idx() = tabular.cellIndex(row, col - 1);
4861         }
4862
4863         if (cur.selIsMultiCell()) {
4864                 cur.pit() = cur.lastpit();
4865                 cur.pos() = cur.lastpos();
4866                 resetPos(cur);
4867                 return;
4868         }
4869
4870         cur.pit() = cur.lastpit();
4871         cur.pos() = cur.lastpos();
4872
4873         // in visual mode, place cursor at extreme left or right
4874         
4875         switch(entry_from) {
4876
4877         case ENTRY_DIRECTION_RIGHT:
4878                 cur.posVisToRowExtremity(false /* !left */);
4879                 break;
4880         case ENTRY_DIRECTION_LEFT:
4881                 cur.posVisToRowExtremity(true /* left */);
4882                 break;
4883         case ENTRY_DIRECTION_IGNORE:
4884                 // nothing to do in this case
4885                 break;
4886
4887         }
4888         cur.setCurrentFont();
4889         resetPos(cur);
4890 }
4891
4892
4893 bool InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
4894 {
4895         istringstream is(argument);
4896         string s;
4897         is >> s;
4898         if (insetCode(s) != TABULAR_CODE)
4899                 return false;
4900
4901         // Safe guard.
4902         size_t safe_guard = 0;
4903         for (;;) {
4904                 if (is.eof())
4905                         break;
4906                 safe_guard++;
4907                 if (safe_guard > 1000) {
4908                         LYXERR0("parameter max count reached!");
4909                         break;
4910                 }
4911                 is >> s;
4912                 Tabular::Feature action = Tabular::LAST_ACTION;
4913
4914                 size_t i = 0;
4915                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4916                         if (s != tabularFeature[i].feature)
4917                                 continue;
4918
4919                         action = tabularFeature[i].action;
4920                         break;
4921                 }
4922                 if (action == Tabular::LAST_ACTION) {
4923                         LYXERR0("Feature not found " << s);
4924                         continue;
4925                 }
4926                 string val;
4927                 if (tabularFeature[i].need_value)
4928                         is >> val;
4929                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
4930                 tabularFeatures(cur, action, val);
4931         }
4932         return true;
4933 }
4934
4935
4936 static void checkLongtableSpecial(Tabular::ltType & ltt,
4937                           string const & special, bool & flag)
4938 {
4939         if (special == "dl_above") {
4940                 ltt.topDL = flag;
4941                 ltt.set = false;
4942         } else if (special == "dl_below") {
4943                 ltt.bottomDL = flag;
4944                 ltt.set = false;
4945         } else if (special == "empty") {
4946                 ltt.empty = flag;
4947                 ltt.set = false;
4948         } else if (flag) {
4949                 ltt.empty = false;
4950                 ltt.set = true;
4951         }
4952 }
4953
4954
4955 bool InsetTabular::oneCellHasRotationState(bool rotated,
4956                 row_type row_start, row_type row_end,
4957                 col_type col_start, col_type col_end) const 
4958 {
4959         for (row_type r = row_start; r <= row_end; ++r)
4960                 for (col_type c = col_start; c <= col_end; ++c)
4961                         if (tabular.getRotateCell(tabular.cellIndex(r, c)) == rotated)
4962                                 return true;
4963
4964         return false;
4965 }
4966
4967 void InsetTabular::tabularFeatures(Cursor & cur,
4968         Tabular::Feature feature, string const & value)
4969 {
4970         col_type sel_col_start;
4971         col_type sel_col_end;
4972         row_type sel_row_start;
4973         row_type sel_row_end;
4974         bool setLines = false;
4975         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4976         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4977
4978         switch (feature) {
4979
4980         case Tabular::M_ALIGN_LEFT:
4981         case Tabular::ALIGN_LEFT:
4982                 setAlign = LYX_ALIGN_LEFT;
4983                 break;
4984
4985         case Tabular::M_ALIGN_RIGHT:
4986         case Tabular::ALIGN_RIGHT:
4987                 setAlign = LYX_ALIGN_RIGHT;
4988                 break;
4989
4990         case Tabular::M_ALIGN_CENTER:
4991         case Tabular::ALIGN_CENTER:
4992                 setAlign = LYX_ALIGN_CENTER;
4993                 break;
4994
4995         case Tabular::ALIGN_BLOCK:
4996                 setAlign = LYX_ALIGN_BLOCK;
4997                 break;
4998
4999         case Tabular::ALIGN_DECIMAL:
5000                 setAlign = LYX_ALIGN_DECIMAL;
5001                 break;
5002
5003         case Tabular::M_VALIGN_TOP:
5004         case Tabular::VALIGN_TOP:
5005                 setVAlign = Tabular::LYX_VALIGN_TOP;
5006                 break;
5007
5008         case Tabular::M_VALIGN_BOTTOM:
5009         case Tabular::VALIGN_BOTTOM:
5010                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
5011                 break;
5012
5013         case Tabular::M_VALIGN_MIDDLE:
5014         case Tabular::VALIGN_MIDDLE:
5015                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
5016                 break;
5017
5018         default:
5019                 break;
5020         }
5021
5022         cur.recordUndoInset(ATOMIC_UNDO);
5023
5024         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5025         row_type const row = tabular.cellRow(cur.idx());
5026         col_type const column = tabular.cellColumn(cur.idx());
5027         bool flag = true;
5028         Tabular::ltType ltt;
5029
5030         switch (feature) {
5031
5032         case Tabular::SET_PWIDTH: {
5033                 Length const len(value);
5034                 tabular.setColumnPWidth(cur, cur.idx(), len);
5035                 if (len.zero()
5036                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
5037                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
5038                 break;
5039         }
5040
5041         case Tabular::SET_MPWIDTH:
5042                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
5043                 break;
5044
5045         case Tabular::SET_SPECIAL_COLUMN:
5046         case Tabular::SET_SPECIAL_MULTICOLUMN:
5047                 if (value == "none")
5048                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
5049                 else
5050                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
5051                 break;
5052
5053         case Tabular::APPEND_ROW:
5054                 // append the row into the tabular
5055                 tabular.appendRow(cur.idx());
5056                 break;
5057
5058         case Tabular::APPEND_COLUMN:
5059                 // append the column into the tabular
5060                 tabular.appendColumn(cur.idx());
5061                 cur.idx() = tabular.cellIndex(row, column);
5062                 break;
5063
5064         case Tabular::DELETE_ROW:
5065                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5066                         tabular.deleteRow(sel_row_start);
5067                 if (sel_row_start >= tabular.nrows())
5068                         --sel_row_start;
5069                 cur.idx() = tabular.cellIndex(sel_row_start, column);
5070                 cur.pit() = 0;
5071                 cur.pos() = 0;
5072                 cur.setSelection(false);
5073                 break;
5074
5075         case Tabular::DELETE_COLUMN:
5076                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5077                         tabular.deleteColumn(sel_col_start);
5078                 if (sel_col_start >= tabular.ncols())
5079                         --sel_col_start;
5080                 cur.idx() = tabular.cellIndex(row, sel_col_start);
5081                 cur.pit() = 0;
5082                 cur.pos() = 0;
5083                 cur.setSelection(false);
5084                 break;
5085
5086         case Tabular::COPY_ROW:
5087                 tabular.copyRow(row);
5088                 break;
5089
5090         case Tabular::COPY_COLUMN:
5091                 tabular.copyColumn(column);
5092                 cur.idx() = tabular.cellIndex(row, column);
5093                 break;
5094
5095         case Tabular::SET_LINE_TOP:
5096         case Tabular::TOGGLE_LINE_TOP: {
5097                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
5098                                ? (value == "true") : !tabular.topLine(cur.idx());
5099                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5100                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5101                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
5102                 break;
5103         }
5104
5105         case Tabular::SET_LINE_BOTTOM:
5106         case Tabular::TOGGLE_LINE_BOTTOM: {
5107                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
5108                                ? (value == "true") : !tabular.bottomLine(cur.idx());
5109                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5110                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5111                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
5112                 break;
5113         }
5114
5115         case Tabular::SET_LINE_LEFT:
5116         case Tabular::TOGGLE_LINE_LEFT: {
5117                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
5118                                ? (value == "true") : !tabular.leftLine(cur.idx());
5119                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5120                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5121                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
5122                 break;
5123         }
5124
5125         case Tabular::SET_LINE_RIGHT:
5126         case Tabular::TOGGLE_LINE_RIGHT: {
5127                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
5128                                ? (value == "true") : !tabular.rightLine(cur.idx());
5129                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5130                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5131                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
5132                 break;
5133         }
5134
5135         case Tabular::M_ALIGN_LEFT:
5136         case Tabular::M_ALIGN_RIGHT:
5137         case Tabular::M_ALIGN_CENTER:
5138                 flag = false;
5139         case Tabular::ALIGN_LEFT:
5140         case Tabular::ALIGN_RIGHT:
5141         case Tabular::ALIGN_CENTER:
5142         case Tabular::ALIGN_BLOCK:
5143         case Tabular::ALIGN_DECIMAL:
5144                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5145                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5146                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign, flag);
5147                 break;
5148
5149         case Tabular::M_VALIGN_TOP:
5150         case Tabular::M_VALIGN_BOTTOM:
5151         case Tabular::M_VALIGN_MIDDLE:
5152                 flag = false;
5153         case Tabular::VALIGN_TOP:
5154         case Tabular::VALIGN_BOTTOM:
5155         case Tabular::VALIGN_MIDDLE:
5156                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5157                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5158                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
5159                 break;
5160
5161         case Tabular::SET_MULTICOLUMN: {
5162                 if (!cur.selection()) {
5163                         // just multicol for one single cell
5164                         // check whether we are completely in a multicol
5165                         if (!tabular.isMultiColumn(cur.idx()))
5166                                 tabular.setMultiColumn(cur.idx(), 1);
5167                         break;
5168                 }
5169                 // we have a selection so this means we just add all this
5170                 // cells to form a multicolumn cell
5171                 idx_type const s_start = cur.selBegin().idx();
5172                 row_type const col_start = tabular.cellColumn(s_start);
5173                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
5174                 cur.idx() = tabular.setMultiColumn(s_start, col_end - col_start + 1);
5175                 cur.pit() = 0;
5176                 cur.pos() = 0;
5177                 cur.setSelection(false);
5178                 break;
5179         }
5180
5181         case Tabular::UNSET_MULTICOLUMN: {
5182                 if (!cur.selection()) {
5183                         if (tabular.isMultiColumn(cur.idx()))
5184                                 tabular.unsetMultiColumn(cur.idx());
5185                         break;
5186                 }
5187         }
5188
5189         case Tabular::MULTICOLUMN: {
5190                 if (tabular.isMultiColumn(cur.idx()))
5191                         tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5192                 else
5193                         tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5194                 break;
5195         }
5196
5197         case Tabular::SET_MULTIROW: {
5198                 if (!cur.selection()) {
5199                         // just multirow for one single cell
5200                         // check whether we are completely in a multirow
5201                         if (!tabular.isMultiRow(cur.idx()))
5202                                 tabular.setMultiRow(cur.idx(), 1);
5203                         break;
5204                 }
5205                 // we have a selection so this means we just add all this
5206                 // cells to form a multirow cell
5207                 idx_type const s_start = cur.selBegin().idx();
5208                 row_type const row_start = tabular.cellRow(s_start);
5209                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5210                 cur.idx() = tabular.setMultiRow(s_start, row_end - row_start + 1);
5211                 cur.pit() = 0;
5212                 cur.pos() = 0;
5213                 cur.setSelection(false);
5214                 break;
5215         }
5216
5217         case Tabular::UNSET_MULTIROW: {
5218                 if (!cur.selection()) {
5219                         if (tabular.isMultiRow(cur.idx()))
5220                                 tabular.unsetMultiRow(cur.idx());
5221                         break;
5222                 }
5223         }
5224
5225         case Tabular::MULTIROW: {
5226                 if (tabular.isMultiRow(cur.idx()))
5227                         tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5228                 else
5229                         tabularFeatures(cur, Tabular::SET_MULTIROW);
5230                 break;
5231         }
5232
5233         case Tabular::SET_ALL_LINES:
5234                 setLines = true;
5235         case Tabular::UNSET_ALL_LINES:
5236                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5237                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5238                                 idx_type const cell = tabular.cellIndex(r, c);
5239                                 tabular.setTopLine(cell, setLines);
5240                                 tabular.setBottomLine(cell, setLines);
5241                                 tabular.setRightLine(cell, setLines);
5242                                 tabular.setLeftLine(cell, setLines);
5243                         }
5244                 break;
5245
5246         case Tabular::SET_BORDER_LINES:
5247                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5248                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
5249                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
5250                 }
5251                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5252                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
5253                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
5254                 }
5255                 break;
5256
5257         case Tabular::SET_LONGTABULAR:
5258                 tabular.is_long_tabular = true;
5259                 break;
5260
5261         case Tabular::UNSET_LONGTABULAR:
5262                 for (row_type r = 0; r < tabular.nrows(); ++r) {
5263                         if (tabular.ltCaption(r)) {
5264                                 cur.idx() = tabular.cellIndex(r, 0);
5265                                 cur.pit() = 0;
5266                                 cur.pos() = 0;
5267                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5268                         }
5269                 }
5270                 tabular.is_long_tabular = false;
5271                 break;
5272
5273         case Tabular::SET_ROTATE_TABULAR:
5274                 tabular.rotate = true;
5275                 break;
5276
5277         case Tabular::UNSET_ROTATE_TABULAR:
5278                 tabular.rotate = false;
5279                 break;
5280
5281         case Tabular::TOGGLE_ROTATE_TABULAR:
5282                 tabular.rotate = !tabular.rotate;
5283                 break;
5284
5285         case Tabular::TABULAR_VALIGN_TOP:
5286                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5287                 break;
5288
5289         case Tabular::TABULAR_VALIGN_MIDDLE:
5290                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5291                 break;
5292
5293         case Tabular::TABULAR_VALIGN_BOTTOM:
5294                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5295                 break;
5296
5297         case Tabular::LONGTABULAR_ALIGN_LEFT:
5298                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5299                 break;
5300
5301         case Tabular::LONGTABULAR_ALIGN_CENTER:
5302                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5303                 break;
5304
5305         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5306                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5307                 break;
5308
5309                 
5310
5311         case Tabular::SET_ROTATE_CELL:
5312                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5313                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5314                                 tabular.setRotateCell(tabular.cellIndex(r, c), true);
5315                 break;
5316
5317         case Tabular::UNSET_ROTATE_CELL:
5318                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5319                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5320                                 tabular.setRotateCell(tabular.cellIndex(r, c), false);
5321                 break;
5322
5323         case Tabular::TOGGLE_ROTATE_CELL:
5324                 {
5325                 bool oneNotRotated = oneCellHasRotationState(false,
5326                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5327
5328                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5329                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5330                                 tabular.setRotateCell(tabular.cellIndex(r, c),
5331                                                                           oneNotRotated);
5332                 }
5333                 break;
5334
5335         case Tabular::SET_USEBOX: {
5336                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5337                 if (val == tabular.getUsebox(cur.idx()))
5338                         val = Tabular::BOX_NONE;
5339                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5340                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5341                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
5342                 break;
5343         }
5344
5345         case Tabular::UNSET_LTFIRSTHEAD:
5346                 flag = false;
5347         case Tabular::SET_LTFIRSTHEAD:
5348                 tabular.getRowOfLTFirstHead(row, ltt);
5349                 checkLongtableSpecial(ltt, value, flag);
5350                 tabular.setLTHead(row, flag, ltt, true);
5351                 break;
5352
5353         case Tabular::UNSET_LTHEAD:
5354                 flag = false;
5355         case Tabular::SET_LTHEAD:
5356                 tabular.getRowOfLTHead(row, ltt);
5357                 checkLongtableSpecial(ltt, value, flag);
5358                 tabular.setLTHead(row, flag, ltt, false);
5359                 break;
5360
5361         case Tabular::UNSET_LTFOOT:
5362                 flag = false;
5363         case Tabular::SET_LTFOOT:
5364                 tabular.getRowOfLTFoot(row, ltt);
5365                 checkLongtableSpecial(ltt, value, flag);
5366                 tabular.setLTFoot(row, flag, ltt, false);
5367                 break;
5368
5369         case Tabular::UNSET_LTLASTFOOT:
5370                 flag = false;
5371         case Tabular::SET_LTLASTFOOT:
5372                 tabular.getRowOfLTLastFoot(row, ltt);
5373                 checkLongtableSpecial(ltt, value, flag);
5374                 tabular.setLTFoot(row, flag, ltt, true);
5375                 break;
5376
5377         case Tabular::SET_LTNEWPAGE:
5378                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
5379                 break;
5380
5381         case Tabular::SET_LTCAPTION: {
5382                 if (tabular.ltCaption(row))
5383                         break;
5384                 cur.idx() = tabular.setLTCaption(row, true);
5385                 cur.pit() = 0;
5386                 cur.pos() = 0;
5387                 cur.setSelection(false);
5388                 // If a row is set as caption, then also insert
5389                 // a caption. Otherwise the LaTeX output is broken.
5390                 lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
5391                 lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
5392                 break;
5393         }
5394         
5395         case Tabular::UNSET_LTCAPTION: {
5396                 if (!tabular.ltCaption(row))
5397                         break;
5398                 cur.idx() = tabular.setLTCaption(row, false);
5399                 cur.pit() = 0;
5400                 cur.pos() = 0;
5401                 cur.setSelection(false);
5402                 FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
5403                 if (lyx::getStatus(fr).enabled())
5404                         lyx::dispatch(fr);
5405                 break;
5406         }
5407
5408         case Tabular::TOGGLE_LTCAPTION: {
5409                 if (tabular.ltCaption(row))
5410                         tabularFeatures(cur, Tabular::UNSET_LTCAPTION);
5411                 else
5412                         tabularFeatures(cur, Tabular::SET_LTCAPTION);
5413                 break;
5414         }
5415
5416         case Tabular::SET_BOOKTABS:
5417                 tabular.use_booktabs = true;
5418                 break;
5419
5420         case Tabular::UNSET_BOOKTABS:
5421                 tabular.use_booktabs = false;
5422                 break;
5423
5424         case Tabular::SET_TOP_SPACE: {
5425                 Length len;
5426                 if (value == "default")
5427                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5428                                 tabular.row_info[r].top_space_default = true;
5429                 else if (value == "none")
5430                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5431                                 tabular.row_info[r].top_space_default = false;
5432                                 tabular.row_info[r].top_space = len;
5433                         }
5434                 else if (isValidLength(value, &len))
5435                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5436                                 tabular.row_info[r].top_space_default = false;
5437                                 tabular.row_info[r].top_space = len;
5438                         }
5439                 break;
5440         }
5441
5442         case Tabular::SET_BOTTOM_SPACE: {
5443                 Length len;
5444                 if (value == "default")
5445                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5446                                 tabular.row_info[r].bottom_space_default = true;
5447                 else if (value == "none")
5448                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5449                                 tabular.row_info[r].bottom_space_default = false;
5450                                 tabular.row_info[r].bottom_space = len;
5451                         }
5452                 else if (isValidLength(value, &len))
5453                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5454                                 tabular.row_info[r].bottom_space_default = false;
5455                                 tabular.row_info[r].bottom_space = len;
5456                         }
5457                 break;
5458         }
5459
5460         case Tabular::SET_INTERLINE_SPACE: {
5461                 Length len;
5462                 if (value == "default")
5463                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5464                                 tabular.row_info[r].interline_space_default = true;
5465                 else if (value == "none")
5466                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5467                                 tabular.row_info[r].interline_space_default = false;
5468                                 tabular.row_info[r].interline_space = len;
5469                         }
5470                 else if (isValidLength(value, &len))
5471                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5472                                 tabular.row_info[r].interline_space_default = false;
5473                                 tabular.row_info[r].interline_space = len;
5474                         }
5475                 break;
5476         }
5477
5478         case Tabular::SET_DECIMAL_POINT:
5479                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5480                         tabular.column_info[c].decimal_point = from_utf8(value);
5481                 break;
5482
5483         // dummy stuff just to avoid warnings
5484         case Tabular::LAST_ACTION:
5485                 break;
5486         }
5487 }
5488
5489
5490 bool InsetTabular::copySelection(Cursor & cur)
5491 {
5492         if (!cur.selection())
5493                 return false;
5494
5495         row_type rs, re;
5496         col_type cs, ce;
5497         getSelection(cur, rs, re, cs, ce);
5498
5499         paste_tabular.reset(new Tabular(tabular));
5500
5501         for (row_type r = 0; r < rs; ++r)
5502                 paste_tabular->deleteRow(0);
5503
5504         row_type const rows = re - rs + 1;
5505         while (paste_tabular->nrows() > rows)
5506                 paste_tabular->deleteRow(rows);
5507
5508         for (col_type c = 0; c < cs; ++c)
5509                 paste_tabular->deleteColumn(0);
5510
5511         col_type const columns = ce - cs + 1;
5512         while (paste_tabular->ncols() > columns)
5513                 paste_tabular->deleteColumn(columns);
5514
5515         paste_tabular->setBuffer(tabular.buffer());
5516
5517         odocstringstream os;
5518         OutputParams const runparams(0);
5519         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5520         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5521         cap::copySelection(cur, os.str());
5522
5523         // mark tabular stack dirty
5524         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5525         // when we (hopefully) have a one-for-all paste mechanism.
5526         // This must be called after cap::copySelection.
5527         dirtyTabularStack(true);
5528
5529         return true;
5530 }
5531
5532
5533 bool InsetTabular::pasteClipboard(Cursor & cur)
5534 {
5535         if (!paste_tabular)
5536                 return false;
5537         col_type actcol = tabular.cellColumn(cur.idx());
5538         row_type actrow = tabular.cellRow(cur.idx());
5539
5540         if (cur.selIsMultiCell()) {
5541                 row_type re;
5542                 col_type ce;
5543                 getSelection(cur, actrow, re, actcol, ce);
5544         }
5545
5546         for (row_type r1 = 0, r2 = actrow;
5547              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
5548              ++r1, ++r2) {
5549                 for (col_type c1 = 0, c2 = actcol;
5550                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
5551                     ++c1, ++c2) {
5552                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5553                               tabular.isPartOfMultiColumn(r2, c2))
5554                                 continue;
5555                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5556                                 --c2;
5557                                 continue;
5558                         }
5559                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5560                                 --c1;
5561                                 continue;
5562                         }
5563                         shared_ptr<InsetTableCell> inset(
5564                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5565                         tabular.setCellInset(r2, c2, inset);
5566                         // FIXME?: why do we need to do this explicitly? (EL)
5567                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
5568
5569                         // FIXME: change tracking (MG)
5570                         inset->setChange(Change(buffer().params().trackChanges ?
5571                                                 Change::INSERTED : Change::UNCHANGED));
5572                         cur.pos() = 0;
5573                 }
5574         }
5575         return true;
5576 }
5577
5578
5579 void InsetTabular::cutSelection(Cursor & cur)
5580 {
5581         if (!cur.selection())
5582                 return;
5583
5584         row_type rs, re;
5585         col_type cs, ce;
5586         getSelection(cur, rs, re, cs, ce);
5587         for (row_type r = rs; r <= re; ++r) {
5588                 for (col_type c = cs; c <= ce; ++c) {
5589                         shared_ptr<InsetTableCell> t
5590                                 = cell(tabular.cellIndex(r, c));
5591                         if (buffer().params().trackChanges)
5592                                 // FIXME: Change tracking (MG)
5593                                 t->setChange(Change(Change::DELETED));
5594                         else
5595                                 t->clear();
5596                 }
5597         }
5598
5599         // cursor position might be invalid now
5600         if (cur.pit() > cur.lastpit())
5601                 cur.pit() = cur.lastpit();
5602         if (cur.pos() > cur.lastpos())
5603                 cur.pos() = cur.lastpos();
5604         cur.clearSelection();
5605 }
5606
5607
5608 bool InsetTabular::isRightToLeft(Cursor & cur) const
5609 {
5610         LASSERT(cur.depth() > 1, /**/);
5611         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5612         pos_type const parentpos = cur[cur.depth() - 2].pos();
5613         return parentpar.getFontSettings(buffer().params(),
5614                                          parentpos).language()->rightToLeft();
5615 }
5616
5617
5618 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5619                                  bool intoInsets)
5620 {
5621         LASSERT(stidx <= enidx, return docstring());
5622         docstring retval;
5623         col_type const col1 = tabular.cellColumn(stidx);
5624         col_type const col2 = tabular.cellColumn(enidx);
5625         row_type const row1 = tabular.cellRow(stidx);
5626         row_type const row2 = tabular.cellRow(enidx);
5627         bool first = true;
5628         for (col_type col = col1; col <= col2; col++)
5629                 for (row_type row = row1; row <= row2; row++) {
5630                         if (!first)
5631                                 retval += "\n";
5632                         else
5633                                 first = false;
5634                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5635                 }
5636         return retval;
5637 }
5638
5639
5640 void InsetTabular::getSelection(Cursor & cur,
5641         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5642 {
5643         CursorSlice const & beg = cur.selBegin();
5644         CursorSlice const & end = cur.selEnd();
5645         cs = tabular.cellColumn(beg.idx());
5646         ce = tabular.cellColumn(end.idx());
5647         if (cs > ce)
5648                 swap(cs, ce);
5649
5650         rs = tabular.cellRow(beg.idx());
5651         re = tabular.cellRow(end.idx());
5652         if (rs > re)
5653                 swap(rs, re);
5654 }
5655
5656
5657 Text * InsetTabular::getText(int idx) const
5658 {
5659         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5660 }
5661
5662
5663 void InsetTabular::setChange(Change const & change)
5664 {
5665         for (idx_type idx = 0; idx < nargs(); ++idx)
5666                 cell(idx)->setChange(change);
5667 }
5668
5669
5670 void InsetTabular::acceptChanges()
5671 {
5672         for (idx_type idx = 0; idx < nargs(); ++idx)
5673                 cell(idx)->acceptChanges();
5674 }
5675
5676
5677 void InsetTabular::rejectChanges()
5678 {
5679         for (idx_type idx = 0; idx < nargs(); ++idx)
5680                 cell(idx)->rejectChanges();
5681 }
5682
5683
5684 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5685 {
5686         return tabular.getPWidth(cell).zero();
5687 }
5688
5689
5690 bool InsetTabular::forcePlainLayout(idx_type cell) const
5691 {
5692         return !tabular.getPWidth(cell).zero();
5693 }
5694
5695
5696 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5697                                      bool usePaste)
5698 {
5699         if (buf.length() <= 0)
5700                 return true;
5701
5702         col_type cols = 1;
5703         row_type rows = 1;
5704         col_type maxCols = 1;
5705         size_t const len = buf.length();
5706         size_t p = 0;
5707
5708         while (p < len &&
5709                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5710                 switch (buf[p]) {
5711                 case '\t':
5712                         ++cols;
5713                         break;
5714                 case '\n':
5715                         if (p + 1 < len)
5716                                 ++rows;
5717                         maxCols = max(cols, maxCols);
5718                         cols = 1;
5719                         break;
5720                 }
5721                 ++p;
5722         }
5723         maxCols = max(cols, maxCols);
5724         Tabular * loctab;
5725         idx_type cell = 0;
5726         col_type ocol = 0;
5727         row_type row = 0;
5728         if (usePaste) {
5729                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
5730                 loctab = paste_tabular.get();
5731                 cols = 0;
5732                 dirtyTabularStack(true);
5733         } else {
5734                 loctab = &tabular;
5735                 cell = bv.cursor().idx();
5736                 ocol = tabular.cellColumn(cell);
5737                 row = tabular.cellRow(cell);
5738         }
5739
5740         size_t op = 0;
5741         idx_type const cells = loctab->numberofcells;
5742         p = 0;
5743         cols = ocol;
5744         rows = loctab->nrows();
5745         col_type const columns = loctab->ncols();
5746
5747         while (cell < cells && p < len && row < rows &&
5748                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
5749         {
5750                 if (p >= len)
5751                         break;
5752                 switch (buf[p]) {
5753                 case '\t':
5754                         // we can only set this if we are not too far right
5755                         if (cols < columns) {
5756                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5757                                 Font const font = bv.textMetrics(&inset->text()).
5758                                         displayFont(0, 0);
5759                                 inset->setText(buf.substr(op, p - op), font,
5760                                                buffer().params().trackChanges);
5761                                 ++cols;
5762                                 ++cell;
5763                         }
5764                         break;
5765                 case '\n':
5766                         // we can only set this if we are not too far right
5767                         if (cols < columns) {
5768                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
5769                                 Font const font = bv.textMetrics(&inset->text()).
5770                                         displayFont(0, 0);
5771                                 inset->setText(buf.substr(op, p - op), font,
5772                                                buffer().params().trackChanges);
5773                         }
5774                         cols = ocol;
5775                         ++row;
5776                         if (row < rows)
5777                                 cell = loctab->cellIndex(row, cols);
5778                         break;
5779                 }
5780                 ++p;
5781                 op = p;
5782         }
5783         // check for the last cell if there is no trailing '\n'
5784         if (cell < cells && op < len) {
5785                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5786                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
5787                 inset->setText(buf.substr(op, len - op), font,
5788                         buffer().params().trackChanges);
5789         }
5790         return true;
5791 }
5792
5793
5794 void InsetTabular::addPreview(DocIterator const & inset_pos,
5795         PreviewLoader & loader) const
5796 {
5797         DocIterator cell_pos = inset_pos;
5798
5799         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
5800         for (row_type r = 0; r < tabular.nrows(); ++r) {
5801                 for (col_type c = 0; c < tabular.ncols(); ++c) {
5802                         cell_pos.top().idx() = tabular.cellIndex(r, c);
5803                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
5804                 }
5805         }
5806 }
5807
5808
5809 bool InsetTabular::completionSupported(Cursor const & cur) const
5810 {
5811         Cursor const & bvCur = cur.bv().cursor();
5812         if (&bvCur.inset() != this)
5813                 return false;
5814         return cur.text()->completionSupported(cur);
5815 }
5816
5817
5818 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
5819 {
5820         return completionSupported(cur);
5821 }
5822
5823
5824 bool InsetTabular::automaticInlineCompletion() const
5825 {
5826         return lyxrc.completion_inline_text;
5827 }
5828
5829
5830 bool InsetTabular::automaticPopupCompletion() const
5831 {
5832         return lyxrc.completion_popup_text;
5833 }
5834
5835
5836 bool InsetTabular::showCompletionCursor() const
5837 {
5838         return lyxrc.completion_cursor_text;
5839 }
5840
5841
5842 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
5843 {
5844         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
5845 }
5846
5847
5848 docstring InsetTabular::completionPrefix(Cursor const & cur) const
5849 {
5850         if (!completionSupported(cur))
5851                 return docstring();
5852         return cur.text()->completionPrefix(cur);
5853 }
5854
5855
5856 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
5857 {
5858         if (!completionSupported(cur))
5859                 return false;
5860
5861         return cur.text()->insertCompletion(cur, s, finished);
5862 }
5863
5864
5865 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
5866                                     Dimension & dim) const
5867 {
5868         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
5869         tm.completionPosAndDim(cur, x, y, dim);
5870 }
5871
5872
5873 void InsetTabular::string2params(string const & in, InsetTabular & inset)
5874 {
5875         istringstream data(in);
5876         Lexer lex;
5877         lex.setStream(data);
5878
5879         if (in.empty())
5880                 return;
5881
5882         string token;
5883         lex >> token;
5884         if (!lex || token != "tabular") {
5885                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
5886                 return;
5887         }
5888
5889         // This is part of the inset proper that is usually swallowed
5890         // by Buffer::readInset
5891         lex >> token;
5892         if (!lex || token != "Tabular") {
5893                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
5894                 return;
5895         }
5896
5897         inset.read(lex);
5898 }
5899
5900
5901 string InsetTabular::params2string(InsetTabular const & inset)
5902 {
5903         ostringstream data;
5904         data << "tabular" << ' ';
5905         inset.write(data);
5906         data << "\\end_inset\n";
5907         return data.str();
5908 }
5909
5910
5911 } // namespace lyx