]> git.lyx.org Git - lyx.git/blob - src/tabular.C
make it compile again (hopefully)
[lyx.git] / src / tabular.C
1 /**
2  * \file tabular.C
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  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "tabular.h"
21
22 #include "buffer.h"
23 #include "bufferparams.h"
24 #include "BufferView.h"
25 #include "cursor.h"
26 #include "debug.h"
27 #include "LaTeXFeatures.h"
28 #include "lyxlex.h"
29 #include "outputparams.h"
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
32
33 #include "insets/insettabular.h"
34
35 #include "support/lstrings.h"
36 #include "support/convert.h"
37
38 #include <sstream>
39
40 using lyx::docstring;
41 using lyx::odocstream;
42 using lyx::support::ltrim;
43 using lyx::support::prefixIs;
44 using lyx::support::rtrim;
45 using lyx::support::suffixIs;
46
47 using boost::shared_ptr;
48 using boost::dynamic_pointer_cast;
49
50 using std::abs;
51 using std::endl;
52 using std::getline;
53 using std::max;
54
55 using std::istream;
56 using std::ostream;
57 using std::ostringstream;
58 using std::vector;
59 using std::string;
60
61 #ifndef CXX_GLOBAL_CSTD
62 using std::strlen;
63 #endif
64
65
66 namespace {
67
68 int const WIDTH_OF_LINE = 5;
69 int const default_line_space = 10;
70
71
72 template <class T>
73 string const write_attribute(string const & name, T const & t)
74 {
75         string const s = tostr(t);
76         return s.empty() ? s : " " + name + "=\"" + s + "\"";
77 }
78
79 template <>
80 string const write_attribute(string const & name, string const & t)
81 {
82         return t.empty() ? t : " " + name + "=\"" + t + "\"";
83 }
84
85
86 template <>
87 string const write_attribute(string const & name, bool const & b)
88 {
89         // we write only true attribute values so we remove a bit of the
90         // file format bloat for tabulars.
91         return b ? write_attribute(name, convert<string>(b)) : string();
92 }
93
94
95 template <>
96 string const write_attribute(string const & name, int const & i)
97 {
98         // we write only true attribute values so we remove a bit of the
99         // file format bloat for tabulars.
100         return i ? write_attribute(name, convert<string>(i)) : string();
101 }
102
103
104 template <>
105 string const write_attribute(string const & name, LyXTabular::idx_type const & i)
106 {
107         // we write only true attribute values so we remove a bit of the
108         // file format bloat for tabulars.
109         return i ? write_attribute(name, convert<string>(i)) : string();
110 }
111
112
113 template <>
114 string const write_attribute(string const & name, LyXLength const & value)
115 {
116         // we write only the value if we really have one same reson as above.
117         return value.zero() ? string() : write_attribute(name, value.asString());
118 }
119
120
121 string const tostr(LyXAlignment const & num)
122 {
123         switch (num) {
124         case LYX_ALIGN_NONE:
125                 return "none";
126         case LYX_ALIGN_BLOCK:
127                 return "block";
128         case LYX_ALIGN_LEFT:
129                 return "left";
130         case LYX_ALIGN_CENTER:
131                 return "center";
132         case LYX_ALIGN_RIGHT:
133                 return "right";
134         case LYX_ALIGN_LAYOUT:
135                 return "layout";
136         case LYX_ALIGN_SPECIAL:
137                 return "special";
138         }
139         return string();
140 }
141
142
143 string const tostr(LyXTabular::VAlignment const & num)
144 {
145         switch (num) {
146         case LyXTabular::LYX_VALIGN_TOP:
147                 return "top";
148         case LyXTabular::LYX_VALIGN_MIDDLE:
149                 return "middle";
150         case LyXTabular::LYX_VALIGN_BOTTOM:
151                 return "bottom";
152         }
153         return string();
154 }
155
156
157 string const tostr(LyXTabular::BoxType const & num)
158 {
159         switch (num) {
160         case LyXTabular::BOX_NONE:
161                 return "none";
162         case LyXTabular::BOX_PARBOX:
163                 return "parbox";
164         case LyXTabular::BOX_MINIPAGE:
165                 return "minipage";
166         }
167         return string();
168 }
169
170
171 // I would have liked a fromstr template a lot better. (Lgb)
172 bool string2type(string const str, LyXAlignment & num)
173 {
174         if (str == "none")
175                 num = LYX_ALIGN_NONE;
176         else if (str == "block")
177                 num = LYX_ALIGN_BLOCK;
178         else if (str == "left")
179                 num = LYX_ALIGN_LEFT;
180         else if (str == "center")
181                 num = LYX_ALIGN_CENTER;
182         else if (str == "right")
183                 num = LYX_ALIGN_RIGHT;
184         else
185                 return false;
186         return true;
187 }
188
189
190 bool string2type(string const str, LyXTabular::VAlignment & num)
191 {
192         if (str == "top")
193                 num = LyXTabular::LYX_VALIGN_TOP;
194         else if (str == "middle" )
195                 num = LyXTabular::LYX_VALIGN_MIDDLE;
196         else if (str == "bottom")
197                 num = LyXTabular::LYX_VALIGN_BOTTOM;
198         else
199                 return false;
200         return true;
201 }
202
203
204 bool string2type(string const str, LyXTabular::BoxType & num)
205 {
206         if (str == "none")
207                 num = LyXTabular::BOX_NONE;
208         else if (str == "parbox")
209                 num = LyXTabular::BOX_PARBOX;
210         else if (str == "minipage")
211                 num = LyXTabular::BOX_MINIPAGE;
212         else
213                 return false;
214         return true;
215 }
216
217
218 bool string2type(string const str, bool & num)
219 {
220         if (str == "true")
221                 num = true;
222         else if (str == "false")
223                 num = false;
224         else
225                 return false;
226         return true;
227 }
228
229
230 bool getTokenValue(string const & str, char const * token, string & ret)
231 {
232         ret.erase();
233         size_t token_length = strlen(token);
234         string::size_type pos = str.find(token);
235
236         if (pos == string::npos || pos + token_length + 1 >= str.length()
237                 || str[pos + token_length] != '=')
238                 return false;
239         pos += token_length + 1;
240         char ch = str[pos];
241         if (ch != '"' && ch != '\'') { // only read till next space
242                 ret += ch;
243                 ch = ' ';
244         }
245         while (pos < str.length() - 1 && str[++pos] != ch)
246                 ret += str[pos];
247
248         return true;
249 }
250
251
252 bool getTokenValue(string const & str, char const * token, int & num)
253 {
254         string tmp;
255         num = 0;
256         if (!getTokenValue(str, token, tmp))
257                 return false;
258         num = convert<int>(tmp);
259         return true;
260 }
261
262
263 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
264 {
265         string tmp;
266         return getTokenValue(str, token, tmp) && string2type(tmp, num);
267 }
268
269
270 bool getTokenValue(string const & str, char const * token,
271                                    LyXTabular::VAlignment & num)
272 {
273         string tmp;
274         return getTokenValue(str, token, tmp) && string2type(tmp, num);
275 }
276
277
278 bool getTokenValue(string const & str, char const * token,
279                                    LyXTabular::BoxType & num)
280 {
281         string tmp;
282         return getTokenValue(str, token, tmp) && string2type(tmp, num);
283 }
284
285
286 bool getTokenValue(string const & str, char const * token, bool & flag)
287 {
288         // set the flag always to false as this should be the default for bools
289         // not in the file-format.
290         flag = false;
291         string tmp;
292         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
293 }
294
295
296 bool getTokenValue(string const & str, char const * token, LyXLength & len)
297 {
298         // set the lenght to be zero() as default as this it should be if not
299         // in the file format.
300         len = LyXLength();
301         string tmp;
302         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
303 }
304
305
306 bool getTokenValue(string const & str, char const * token, LyXLength & len, bool & flag)
307 {
308         len = LyXLength();
309         flag = false;
310         string tmp;
311         if (!getTokenValue(str, token, tmp))
312                 return false;
313         if (tmp == "default") {
314                 flag = true;
315                 return  true;
316         }
317         return isValidLength(tmp, &len);
318 }
319
320
321 void l_getline(istream & is, string & str)
322 {
323         str.erase();
324         while (str.empty()) {
325                 getline(is, str);
326                 if (!str.empty() && str[str.length() - 1] == '\r')
327                         str.erase(str.length() - 1);
328         }
329 }
330
331 } // namespace
332
333 /// Define a few methods for the inner structs
334
335 LyXTabular::cellstruct::cellstruct(BufferParams const & bp)
336         : cellno(0),
337           width_of_cell(0),
338           multicolumn(LyXTabular::CELL_NORMAL),
339           alignment(LYX_ALIGN_CENTER),
340           valignment(LYX_VALIGN_TOP),
341           top_line(true),
342           bottom_line(false),
343           left_line(true),
344           right_line(false),
345           usebox(BOX_NONE),
346           rotate(false),
347           inset(new InsetText(bp))
348 {}
349
350
351 LyXTabular::cellstruct::cellstruct(cellstruct const & cs)
352         : cellno(cs.cellno),
353           width_of_cell(cs.width_of_cell),
354           multicolumn(cs.multicolumn),
355           alignment(cs.alignment),
356           valignment(cs.valignment),
357           top_line(cs.top_line),
358           bottom_line(cs.bottom_line),
359           left_line(cs.left_line),
360           right_line(cs.right_line),
361           usebox(cs.usebox),
362           rotate(cs.rotate),
363           align_special(cs.align_special),
364           p_width(cs.p_width),
365           inset(dynamic_cast<InsetText*>(cs.inset->clone().release()))
366 {}
367
368
369 LyXTabular::cellstruct &
370 LyXTabular::cellstruct::operator=(cellstruct cs)
371 {
372         swap(cs);
373         return *this;
374 }
375
376
377 void
378 LyXTabular::cellstruct::swap(cellstruct & rhs)
379 {
380         std::swap(cellno, rhs.cellno);
381         std::swap(width_of_cell, rhs.width_of_cell);
382         std::swap(multicolumn, rhs.multicolumn);
383         std::swap(alignment, rhs.alignment);
384         std::swap(valignment, rhs.valignment);
385         std::swap(top_line, rhs.top_line);
386         std::swap(bottom_line, rhs.bottom_line);
387         std::swap(left_line, rhs.left_line);
388         std::swap(right_line, rhs.right_line);
389         std::swap(usebox, rhs.usebox);
390         std::swap(rotate, rhs.rotate);
391         std::swap(align_special, rhs.align_special);
392         p_width.swap(rhs.p_width);
393         inset.swap(rhs.inset);
394 }
395
396
397 LyXTabular::rowstruct::rowstruct()
398         : ascent_of_row(0),
399           descent_of_row(0),
400           top_line(true),
401           bottom_line(false),
402           top_space_default(false),
403           bottom_space_default(false),
404           interline_space_default(false),
405           endhead(false),
406           endfirsthead(false),
407           endfoot(false),
408           endlastfoot(false),
409           newpage(false)
410 {}
411
412
413 LyXTabular::columnstruct::columnstruct()
414         : alignment(LYX_ALIGN_CENTER),
415           valignment(LYX_VALIGN_TOP),
416           left_line(true),
417           right_line(false),
418           width_of_column(0)
419 {
420 }
421
422
423 LyXTabular::ltType::ltType()
424         : topDL(false),
425           bottomDL(false),
426           empty(false)
427 {}
428
429
430 LyXTabular::LyXTabular(BufferParams const & bp, row_type rows_arg,
431                        col_type columns_arg)
432 {
433         init(bp, rows_arg, columns_arg);
434 }
435
436
437 // activates all lines and sets all widths to 0
438 void LyXTabular::init(BufferParams const & bp, row_type rows_arg,
439                       col_type columns_arg)
440 {
441         rows_    = rows_arg;
442         columns_ = columns_arg;
443         row_info = row_vector(rows_);
444         column_info = column_vector(columns_);
445         cell_info = cell_vvector(rows_, cell_vector(columns_, cellstruct(bp)));
446         row_info.reserve(10);
447         column_info.reserve(10);
448         cell_info.reserve(100);
449         fixCellNums();
450         for (row_type i = 0; i < rows_; ++i)
451                 cell_info[i].back().right_line = true;
452         row_info.back().bottom_line = true;
453         row_info.front().bottom_line = true;
454         column_info.back().right_line = true;
455         is_long_tabular = false;
456         rotate = false;
457         use_booktabs = false;
458 }
459
460
461 void LyXTabular::fixCellNums()
462 {
463         idx_type cellno = 0;
464         for (row_type i = 0; i < rows_; ++i) {
465                 for (col_type j = 0; j < columns_; ++j) {
466                         // When debugging it can be nice to set
467                         // this to true.
468                         cell_info[i][j].inset->setDrawFrame(false);
469                         cell_info[i][j].cellno = cellno++;
470                 }
471                 cell_info[i].back().right_line = true;
472         }
473
474         set_row_column_number_info();
475 }
476
477
478 void LyXTabular::appendRow(BufferParams const & bp, idx_type const cell)
479 {
480         ++rows_;
481
482         row_type const row = row_of_cell(cell);
483
484         row_vector::iterator rit = row_info.begin() + row;
485         row_info.insert(rit, rowstruct());
486         // now set the values of the row before
487         row_info[row] = row_info[row + 1];
488
489         cell_vvector old(rows_ - 1);
490         for (row_type i = 0; i < rows_ - 1; ++i)
491                 swap(cell_info[i], old[i]);
492
493         cell_info = cell_vvector(rows_, cell_vector(columns_, cellstruct(bp)));
494
495         for (row_type i = 0; i <= row; ++i)
496                 swap(cell_info[i], old[i]);
497         for (row_type i = row + 2; i < rows_; ++i)
498                 swap(cell_info[i], old[i - 1]);
499
500         if (bp.trackChanges)
501                 // FIXME: Change Tracking (MG)
502                 for (col_type j = 0; j < columns_; ++j)
503                         cell_info[row + 1][j].inset->markNew(true);
504
505         set_row_column_number_info();
506 }
507
508
509 void LyXTabular::deleteRow(row_type const row)
510 {
511         // Not allowed to delete last row
512         if (rows_ == 1)
513                 return;
514
515         row_info.erase(row_info.begin() + row);
516         cell_info.erase(cell_info.begin() + row);
517         --rows_;
518         fixCellNums();
519 }
520
521
522 void LyXTabular::copyRow(BufferParams const & bp, row_type const row)
523 {
524         ++rows_;
525
526         row_info.insert(row_info.begin() + row, row_info[row]);
527         cell_info.insert(cell_info.begin() + row, cell_info[row]);
528
529         if (bp.trackChanges)
530                 // FIXME: Change Tracking (MG)
531                 for (col_type j = 0; j < columns_; ++j)
532                         cell_info[row + 1][j].inset->markNew(true);
533
534         set_row_column_number_info();
535 }
536
537
538 void LyXTabular::appendColumn(BufferParams const & bp, idx_type const cell)
539 {
540         ++columns_;
541
542         col_type const column = column_of_cell(cell);
543         column_vector::iterator cit = column_info.begin() + column + 1;
544         column_info.insert(cit, columnstruct());
545         // set the column values of the column before
546         column_info[column + 1] = column_info[column];
547
548         for (row_type i = 0; i < rows_; ++i) {
549                 cell_info[i].insert(cell_info[i].begin() + column + 1, cellstruct(bp));
550
551                 // care about multicolumns
552                 if (cell_info[i][column + 1].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
553                         cell_info[i][column + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
554
555                 if (column + 2 >= columns_
556                     || cell_info[i][column + 2].multicolumn != CELL_PART_OF_MULTICOLUMN)
557                         cell_info[i][column + 1].multicolumn = LyXTabular::CELL_NORMAL;
558         }
559         //++column;
560         for (row_type i = 0; i < rows_; ++i) {
561                 cell_info[i][column + 1].inset->clear();
562                 if (bp.trackChanges)
563                         // FIXME: Change Tracking (MG)
564                         cell_info[i][column + 1].inset->markNew(true);
565         }
566         fixCellNums();
567 }
568
569
570 void LyXTabular::deleteColumn(col_type const column)
571 {
572         // Not allowed to delete last column
573         if (columns_ == 1)
574                 return;
575
576         column_info.erase(column_info.begin() + column);
577         for (row_type i = 0; i < rows_; ++i)
578                 cell_info[i].erase(cell_info[i].begin() + column);
579         --columns_;
580         fixCellNums();
581 }
582
583
584 void LyXTabular::copyColumn(BufferParams const & bp, col_type const column)
585 {
586         ++columns_;
587
588         column_info.insert(column_info.begin() + column, column_info[column]);
589
590         for (row_type i = 0; i < rows_; ++i)
591                 cell_info[i].insert(cell_info[i].begin() + column, cell_info[i][column]);
592
593         if (bp.trackChanges)
594                 // FIXME: Change Tracking (MG)
595                 for (row_type i = 0; i < rows_; ++i)
596                         cell_info[i][column + 1].inset->markNew(true);
597         fixCellNums();
598 }
599
600
601 void LyXTabular::set_row_column_number_info()
602 {
603         numberofcells = 0;
604         for (row_type row = 0; row < rows_; ++row) {
605                 for (col_type column = 0; column < columns_; ++column) {
606                         if (cell_info[row][column].multicolumn
607                                 != LyXTabular::CELL_PART_OF_MULTICOLUMN)
608                                 ++numberofcells;
609                         if (numberofcells == 0)
610                                 // FIXME: Is this intended?
611                                 cell_info[row][column].cellno = npos;
612                         else
613                                 cell_info[row][column].cellno =
614                                         numberofcells - 1;
615                 }
616         }
617
618         rowofcell.resize(numberofcells);
619         columnofcell.resize(numberofcells);
620
621         row_type row = 0;
622         col_type column = 0;
623         for (idx_type c = 0;
624                  c < numberofcells && row < rows_ && column < columns_;) {
625                 rowofcell[c] = row;
626                 columnofcell[c] = column;
627                 ++c;
628                 do {
629                         ++column;
630                 } while (column < columns_ &&
631                                  cell_info[row][column].multicolumn
632                                  == LyXTabular::CELL_PART_OF_MULTICOLUMN);
633
634                 if (column == columns_) {
635                         column = 0;
636                         ++row;
637                 }
638         }
639
640         for (row_type row = 0; row < rows_; ++row) {
641                 for (col_type column = 0; column < columns_; ++column) {
642                         if (isPartOfMultiColumn(row,column))
643                                 continue;
644                         cell_info[row][column].inset->setAutoBreakRows(
645                                 !getPWidth(getCellNumber(row, column)).zero());
646                 }
647         }
648 }
649
650
651 LyXTabular::idx_type LyXTabular::getNumberOfCells() const
652 {
653         return numberofcells;
654 }
655
656
657 LyXTabular::idx_type LyXTabular::numberOfCellsInRow(idx_type const cell) const
658 {
659         row_type const row = row_of_cell(cell);
660         idx_type result = 0;
661         for (col_type i = 0; i < columns_; ++i)
662                 if (cell_info[row][i].multicolumn != LyXTabular::CELL_PART_OF_MULTICOLUMN)
663                         ++result;
664         return result;
665 }
666
667
668 bool LyXTabular::topLine(idx_type const cell, bool const onlycolumn) const
669 {
670         if (!onlycolumn && isMultiColumn(cell) &&
671             !(use_booktabs && row_of_cell(cell) == 0))
672                 return cellinfo_of_cell(cell).top_line;
673         return row_info[row_of_cell(cell)].top_line;
674 }
675
676
677 bool LyXTabular::bottomLine(idx_type const cell, bool onlycolumn) const
678 {
679         if (!onlycolumn && isMultiColumn(cell) &&
680             !(use_booktabs && isLastRow(cell)))
681                 return cellinfo_of_cell(cell).bottom_line;
682         return row_info[row_of_cell(cell)].bottom_line;
683 }
684
685
686 bool LyXTabular::leftLine(idx_type cell, bool onlycolumn) const
687 {
688         if (use_booktabs)
689                 return false;
690         if (!onlycolumn && isMultiColumn(cell) &&
691                 (isFirstCellInRow(cell) || isMultiColumn(cell-1)))
692         {
693                 if (cellinfo_of_cell(cell).align_special.empty())
694                         return cellinfo_of_cell(cell).left_line;
695                 return prefixIs(ltrim(cellinfo_of_cell(cell).align_special), "|");
696         }
697         if (column_info[column_of_cell(cell)].align_special.empty())
698                 return column_info[column_of_cell(cell)].left_line;
699         return prefixIs(ltrim(column_info[column_of_cell(cell)].align_special), "|");
700 }
701
702
703 bool LyXTabular::rightLine(idx_type cell, bool onlycolumn) const
704 {
705         if (use_booktabs)
706                 return false;
707         if (!onlycolumn && isMultiColumn(cell) &&
708                 (isLastCellInRow(cell) || isMultiColumn(cell + 1)))
709         {
710                 if (cellinfo_of_cell(cell).align_special.empty())
711                         return cellinfo_of_cell(cell).right_line;
712                 return suffixIs(rtrim(cellinfo_of_cell(cell).align_special), "|");
713         }
714         if (column_info[column_of_cell(cell)].align_special.empty())
715                 return column_info[right_column_of_cell(cell)].right_line;
716         return suffixIs(rtrim(column_info[column_of_cell(cell)].align_special), "|");
717 }
718
719
720 bool LyXTabular::topAlreadyDrawn(idx_type cell) const
721 {
722         row_type row = row_of_cell(cell);
723         if (row > 0 && !getAdditionalHeight(row)) {
724                 col_type column = column_of_cell(cell);
725                 --row;
726                 while (column
727                            && cell_info[row][column].multicolumn
728                            == LyXTabular::CELL_PART_OF_MULTICOLUMN)
729                         --column;
730                 if (cell_info[row][column].multicolumn == LyXTabular::CELL_NORMAL)
731                         return row_info[row].bottom_line;
732                 else
733                         return cell_info[row][column].bottom_line;
734         }
735         return false;
736 }
737
738
739 bool LyXTabular::leftAlreadyDrawn(idx_type cell) const
740 {
741         col_type column = column_of_cell(cell);
742         if (column > 0) {
743                 row_type row = row_of_cell(cell);
744                 while (--column &&
745                            (cell_info[row][column].multicolumn ==
746                                 LyXTabular::CELL_PART_OF_MULTICOLUMN));
747                 if (getAdditionalWidth(cell_info[row][column].cellno))
748                         return false;
749                 return rightLine(cell_info[row][column].cellno);
750         }
751         return false;
752 }
753
754
755 bool LyXTabular::isLastRow(idx_type cell) const
756 {
757         return row_of_cell(cell) == rows_ - 1;
758 }
759
760
761 int LyXTabular::getAdditionalHeight(row_type row) const
762 {
763         if (!row || row >= rows_)
764                 return 0;
765
766         bool top = true;
767         bool bottom = true;
768
769         for (col_type column = 0; column < columns_ && bottom; ++column) {
770                 switch (cell_info[row - 1][column].multicolumn) {
771                 case LyXTabular::CELL_BEGIN_OF_MULTICOLUMN:
772                         bottom = cell_info[row - 1][column].bottom_line;
773                         break;
774                 case LyXTabular::CELL_NORMAL:
775                         bottom = row_info[row - 1].bottom_line;
776                 }
777         }
778         for (col_type column = 0; column < columns_ && top; ++column) {
779                 switch (cell_info[row][column].multicolumn) {
780                 case LyXTabular::CELL_BEGIN_OF_MULTICOLUMN:
781                         top = cell_info[row][column].top_line;
782                         break;
783                 case LyXTabular::CELL_NORMAL:
784                         top = row_info[row].top_line;
785                 }
786         }
787         int const interline_space = row_info[row - 1].interline_space_default ?
788                 default_line_space :
789                 row_info[row - 1].interline_space.inPixels(width_of_tabular);
790         if (top && bottom)
791                 return interline_space + WIDTH_OF_LINE;
792         return interline_space;
793 }
794
795
796 int LyXTabular::getAdditionalWidth(idx_type cell) const
797 {
798         // internally already set in setWidthOfCell
799         // used to get it back in text.C
800         col_type const col = right_column_of_cell(cell);
801         row_type const row = row_of_cell(cell);
802         if (col < columns_ - 1 && rightLine(cell) &&
803                 leftLine(cell_info[row][col+1].cellno)) // column_info[col+1].left_line)
804         {
805                 return WIDTH_OF_LINE;
806         }
807         return 0;
808 }
809
810
811 // returns the maximum over all rows
812 int LyXTabular::getWidthOfColumn(idx_type cell) const
813 {
814         col_type const column1 = column_of_cell(cell);
815         col_type const column2 = right_column_of_cell(cell);
816         int result = 0;
817         for (col_type i = column1; i <= column2; ++i)
818                 result += column_info[i].width_of_column;
819         return result;
820 }
821
822
823 int LyXTabular::getWidthOfTabular() const
824 {
825         return width_of_tabular;
826 }
827
828
829 // returns true if a complete update is necessary, otherwise false
830 bool LyXTabular::setWidthOfMulticolCell(idx_type cell, int new_width)
831 {
832         if (!isMultiColumn(cell))
833                 return false;
834
835         row_type const row = row_of_cell(cell);
836         col_type const column1 = column_of_cell(cell);
837         col_type const column2 = right_column_of_cell(cell);
838         int const old_val = cell_info[row][column2].width_of_cell;
839
840         // first set columns to 0 so we can calculate the right width
841         for (col_type i = column1; i <= column2; ++i) {
842                 cell_info[row][i].width_of_cell = 0;
843         }
844         // set the width to MAX_WIDTH until width > 0
845         int width = new_width + 2 * WIDTH_OF_LINE;
846         col_type i = column1;
847         for (; i < column2 && width > column_info[i].width_of_column; ++i) {
848                 cell_info[row][i].width_of_cell = column_info[i].width_of_column;
849                 width -= column_info[i].width_of_column;
850         }
851         if (width > 0) {
852                 cell_info[row][i].width_of_cell = width;
853         }
854         if (old_val != cell_info[row][column2].width_of_cell) {
855                 // in this case we have to recalculate all multicolumn cells which
856                 // have this column as one of theirs but not as last one
857                 calculate_width_of_column_NMC(i);
858                 recalculateMulticolumnsOfColumn(i);
859                 calculate_width_of_column(i);
860         }
861         return true;
862 }
863
864
865 void LyXTabular::recalculateMulticolumnsOfColumn(col_type column)
866 {
867         // the last column does not have to be recalculated because all
868         // multicolumns will have here there last multicolumn cell which
869         // always will have the whole rest of the width of the cell.
870         if (columns_ < 2 || column > (columns_ - 2))
871                 return;
872         for (row_type row = 0; row < rows_; ++row) {
873                 int mc = cell_info[row][column].multicolumn;
874                 int nmc = cell_info[row][column+1].multicolumn;
875                 // we only have to update multicolumns which do not have this
876                 // column as their last column!
877                 if (mc == CELL_BEGIN_OF_MULTICOLUMN ||
878                           (mc == CELL_PART_OF_MULTICOLUMN &&
879                            nmc == CELL_PART_OF_MULTICOLUMN))
880                 {
881                         idx_type const cellno = cell_info[row][column].cellno;
882                         setWidthOfMulticolCell(cellno,
883                                                getWidthOfCell(cellno) - 2 * WIDTH_OF_LINE);
884                 }
885         }
886 }
887
888
889 void LyXTabular::setWidthOfCell(idx_type cell, int new_width)
890 {
891         row_type const row = row_of_cell(cell);
892         col_type const column1 = column_of_cell(cell);
893         bool tmp = false;
894         int width = 0;
895         int add_width = 0;
896
897         if (rightLine(cell_info[row][column1].cellno, true) &&
898                 column1 < columns_ - 1 &&
899                 leftLine(cell_info[row][column1+1].cellno, true))
900         {
901                 add_width = WIDTH_OF_LINE;
902         }
903
904         if (getWidthOfCell(cell) == new_width + 2 * WIDTH_OF_LINE + add_width)
905                 return;
906
907         if (isMultiColumnReal(cell)) {
908                 tmp = setWidthOfMulticolCell(cell, new_width);
909         } else {
910                 width = new_width + 2 * WIDTH_OF_LINE + add_width;
911                 cell_info[row][column1].width_of_cell = width;
912                 tmp = calculate_width_of_column_NMC(column1);
913                 if (tmp)
914                         recalculateMulticolumnsOfColumn(column1);
915         }
916         if (tmp) {
917                 for (col_type i = 0; i < columns_; ++i)
918                         calculate_width_of_column(i);
919                 calculate_width_of_tabular();
920         }
921 }
922
923
924 void LyXTabular::setAlignment(idx_type cell, LyXAlignment align,
925                               bool onlycolumn)
926 {
927         if (!isMultiColumn(cell) || onlycolumn)
928                 column_info[column_of_cell(cell)].alignment = align;
929         if (!onlycolumn)
930                 cellinfo_of_cell(cell).alignment = align;
931 }
932
933
934 void LyXTabular::setVAlignment(idx_type cell, VAlignment align,
935                                bool onlycolumn)
936 {
937         if (!isMultiColumn(cell) || onlycolumn)
938                 column_info[column_of_cell(cell)].valignment = align;
939         if (!onlycolumn)
940                 cellinfo_of_cell(cell).valignment = align;
941 }
942
943
944 namespace {
945
946 /**
947  * Allow line and paragraph breaks for fixed width cells or disallow them,
948  * merge cell paragraphs and reset layout to standard for variable width
949  * cells.
950  */
951 void toggleFixedWidth(LCursor & cur, InsetText * inset, bool fixedWidth)
952 {
953         inset->setAutoBreakRows(fixedWidth);
954         if (fixedWidth)
955                 return;
956
957         // merge all paragraphs to one
958         BufferParams const & bp =
959                 inset->getText(0)->bv_owner->buffer()->params();
960         while (inset->paragraphs().size() > 1)
961                 mergeParagraph(bp, inset->paragraphs(), 0);
962
963         // reset layout
964         cur.push(*inset);
965         // undo information has already been recorded
966         inset->getText(0)->setLayout(0, cur.lastpit() + 1,
967                         bp.getLyXTextClass().defaultLayoutName());
968         cur.pop();
969 }
970
971 }
972
973
974 void LyXTabular::setColumnPWidth(LCursor & cur, idx_type cell,
975                 LyXLength const & width)
976 {
977         col_type const j = column_of_cell(cell);
978
979         column_info[j].p_width = width;
980         for (row_type i = 0; i < rows_; ++i) {
981                 idx_type const cell = getCellNumber(i, j);
982                 // because of multicolumns
983                 toggleFixedWidth(cur, getCellInset(cell).get(),
984                                  !getPWidth(cell).zero());
985         }
986         // cur paragraph can become invalid after paragraphs were merged
987         if (cur.pit() > cur.lastpit())
988                 cur.pit() = cur.lastpit();
989         // cur position can become invalid after newlines were removed
990         if (cur.pos() > cur.lastpos())
991                 cur.pos() = cur.lastpos();
992 }
993
994
995 bool LyXTabular::setMColumnPWidth(LCursor & cur, idx_type cell,
996                 LyXLength const & width)
997 {
998         if (!isMultiColumn(cell))
999                 return false;
1000
1001         cellinfo_of_cell(cell).p_width = width;
1002         toggleFixedWidth(cur, getCellInset(cell).get(), !width.zero());
1003         // cur paragraph can become invalid after paragraphs were merged
1004         if (cur.pit() > cur.lastpit())
1005                 cur.pit() = cur.lastpit();
1006         // cur position can become invalid after newlines were removed
1007         if (cur.pos() > cur.lastpos())
1008                 cur.pos() = cur.lastpos();
1009         return true;
1010 }
1011
1012
1013 void LyXTabular::setAlignSpecial(idx_type cell, string const & special,
1014                                  LyXTabular::Feature what)
1015 {
1016         if (what == SET_SPECIAL_MULTI)
1017                 cellinfo_of_cell(cell).align_special = special;
1018         else
1019                 column_info[column_of_cell(cell)].align_special = special;
1020 }
1021
1022
1023 void LyXTabular::setAllLines(idx_type cell, bool line)
1024 {
1025         setTopLine(cell, line);
1026         setBottomLine(cell, line);
1027         setRightLine(cell, line);
1028         setLeftLine(cell, line);
1029 }
1030
1031
1032 void LyXTabular::setTopLine(idx_type cell, bool line, bool onlycolumn)
1033 {
1034         row_type const row = row_of_cell(cell);
1035         if (onlycolumn || !isMultiColumn(cell))
1036                 row_info[row].top_line = line;
1037         else
1038                 cellinfo_of_cell(cell).top_line = line;
1039 }
1040
1041
1042 void LyXTabular::setBottomLine(idx_type cell, bool line, bool onlycolumn)
1043 {
1044         if (onlycolumn || !isMultiColumn(cell))
1045                 row_info[row_of_cell(cell)].bottom_line = line;
1046         else
1047                 cellinfo_of_cell(cell).bottom_line = line;
1048 }
1049
1050
1051 void LyXTabular::setLeftLine(idx_type cell, bool line, bool onlycolumn)
1052 {
1053         if (onlycolumn || !isMultiColumn(cell))
1054                 column_info[column_of_cell(cell)].left_line = line;
1055         else
1056                 cellinfo_of_cell(cell).left_line = line;
1057 }
1058
1059
1060 void LyXTabular::setRightLine(idx_type cell, bool line, bool onlycolumn)
1061 {
1062         if (onlycolumn || !isMultiColumn(cell))
1063                 column_info[right_column_of_cell(cell)].right_line = line;
1064         else
1065                 cellinfo_of_cell(cell).right_line = line;
1066 }
1067
1068
1069 LyXAlignment LyXTabular::getAlignment(idx_type cell, bool onlycolumn) const
1070 {
1071         if (!onlycolumn && isMultiColumn(cell))
1072                 return cellinfo_of_cell(cell).alignment;
1073         return column_info[column_of_cell(cell)].alignment;
1074 }
1075
1076
1077 LyXTabular::VAlignment
1078 LyXTabular::getVAlignment(idx_type cell, bool onlycolumn) const
1079 {
1080         if (!onlycolumn && isMultiColumn(cell))
1081                 return cellinfo_of_cell(cell).valignment;
1082         return column_info[column_of_cell(cell)].valignment;
1083 }
1084
1085
1086 LyXLength const LyXTabular::getPWidth(idx_type cell) const
1087 {
1088         if (isMultiColumn(cell))
1089                 return cellinfo_of_cell(cell).p_width;
1090         return column_info[column_of_cell(cell)].p_width;
1091 }
1092
1093
1094 LyXLength const LyXTabular::getColumnPWidth(idx_type cell) const
1095 {
1096         return column_info[column_of_cell(cell)].p_width;
1097 }
1098
1099
1100 LyXLength const LyXTabular::getMColumnPWidth(idx_type cell) const
1101 {
1102         if (isMultiColumn(cell))
1103                 return cellinfo_of_cell(cell).p_width;
1104         return LyXLength();
1105 }
1106
1107
1108 string const LyXTabular::getAlignSpecial(idx_type cell, int what) const
1109 {
1110         if (what == SET_SPECIAL_MULTI)
1111                 return cellinfo_of_cell(cell).align_special;
1112         return column_info[column_of_cell(cell)].align_special;
1113 }
1114
1115
1116 int LyXTabular::getWidthOfCell(idx_type cell) const
1117 {
1118         row_type const row = row_of_cell(cell);
1119         col_type const column1 = column_of_cell(cell);
1120         col_type const column2 = right_column_of_cell(cell);
1121         int result = 0;
1122         for (col_type i = column1; i <= column2; ++i)
1123                 result += cell_info[row][i].width_of_cell;
1124         return result;
1125 }
1126
1127
1128 int LyXTabular::getBeginningOfTextInCell(idx_type cell) const
1129 {
1130         int x = 0;
1131
1132         switch (getAlignment(cell)) {
1133         case LYX_ALIGN_CENTER:
1134                 x += (getWidthOfColumn(cell) - getWidthOfCell(cell)) / 2;
1135                 break;
1136         case LYX_ALIGN_RIGHT:
1137                 x += getWidthOfColumn(cell) - getWidthOfCell(cell);
1138                 // + getAdditionalWidth(cell);
1139                 break;
1140         default:
1141                 // LYX_ALIGN_LEFT: nothing :-)
1142                 break;
1143         }
1144
1145         // the LaTeX Way :-(
1146         x += WIDTH_OF_LINE;
1147         return x;
1148 }
1149
1150
1151 bool LyXTabular::isFirstCellInRow(idx_type cell) const
1152 {
1153         return column_of_cell(cell) == 0;
1154 }
1155
1156
1157 LyXTabular::idx_type LyXTabular::getFirstCellInRow(row_type row) const
1158 {
1159         if (row > rows_ - 1)
1160                 row = rows_ - 1;
1161         return cell_info[row][0].cellno;
1162 }
1163
1164
1165 bool LyXTabular::isLastCellInRow(idx_type cell) const
1166 {
1167         return right_column_of_cell(cell) == columns_ - 1;
1168 }
1169
1170
1171 LyXTabular::idx_type LyXTabular::getLastCellInRow(row_type row) const
1172 {
1173         if (row > rows_ - 1)
1174                 row = rows_ - 1;
1175         return cell_info[row][columns_-1].cellno;
1176 }
1177
1178
1179 void LyXTabular::calculate_width_of_column(col_type column)
1180 {
1181         int maximum = 0;
1182         for (row_type i = 0; i < rows_; ++i)
1183                 maximum = max(cell_info[i][column].width_of_cell, maximum);
1184         column_info[column].width_of_column = maximum;
1185 }
1186
1187
1188 //
1189 // Calculate the columns regarding ONLY the normal cells and if this
1190 // column is inside a multicolumn cell then use it only if its the last
1191 // column of this multicolumn cell as this gives an added width to the
1192 // column, all the rest should be adapted!
1193 //
1194 bool LyXTabular::calculate_width_of_column_NMC(col_type column)
1195 {
1196         int const old_column_width = column_info[column].width_of_column;
1197         int max = 0;
1198         for (row_type i = 0; i < rows_; ++i) {
1199                 idx_type cell = getCellNumber(i, column);
1200                 bool ismulti = isMultiColumnReal(cell);
1201                 if ((!ismulti || column == right_column_of_cell(cell)) &&
1202                         cell_info[i][column].width_of_cell > max)
1203                 {
1204                         max = cell_info[i][column].width_of_cell;
1205                 }
1206         }
1207         column_info[column].width_of_column = max;
1208         return column_info[column].width_of_column != old_column_width;
1209 }
1210
1211
1212 void LyXTabular::calculate_width_of_tabular()
1213 {
1214         width_of_tabular = 0;
1215         for (col_type i = 0; i < columns_; ++i)
1216                 width_of_tabular += column_info[i].width_of_column;
1217 }
1218
1219
1220 LyXTabular::row_type LyXTabular::row_of_cell(idx_type cell) const
1221 {
1222         if (cell >= numberofcells)
1223                 return rows_ - 1;
1224         if (cell == npos)
1225                 return 0;
1226         return rowofcell[cell];
1227 }
1228
1229
1230 LyXTabular::col_type LyXTabular::column_of_cell(idx_type cell) const
1231 {
1232         if (cell >= numberofcells)
1233                 return columns_ - 1;
1234         if (cell == npos)
1235                 return 0;
1236         return columnofcell[cell];
1237 }
1238
1239
1240 LyXTabular::col_type LyXTabular::right_column_of_cell(idx_type cell) const
1241 {
1242         row_type const row = row_of_cell(cell);
1243         col_type column = column_of_cell(cell);
1244         while (column < columns_ - 1 &&
1245                    cell_info[row][column + 1].multicolumn == LyXTabular::CELL_PART_OF_MULTICOLUMN)
1246                 ++column;
1247         return column;
1248 }
1249
1250
1251 void LyXTabular::write(Buffer const & buf, ostream & os) const
1252 {
1253         // header line
1254         os << "<lyxtabular"
1255            << write_attribute("version", 3)
1256            << write_attribute("rows", rows_)
1257            << write_attribute("columns", columns_)
1258            << ">\n";
1259         // global longtable options
1260         os << "<features"
1261            << write_attribute("rotate", rotate)
1262            << write_attribute("booktabs", use_booktabs)
1263            << write_attribute("islongtable", is_long_tabular)
1264            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1265            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1266            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1267            << write_attribute("headTopDL", endhead.topDL)
1268            << write_attribute("headBottomDL", endhead.bottomDL)
1269            << write_attribute("footTopDL", endfoot.topDL)
1270            << write_attribute("footBottomDL", endfoot.bottomDL)
1271            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1272            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1273            << write_attribute("lastFootEmpty", endlastfoot.empty)
1274            << ">\n";
1275         for (col_type j = 0; j < columns_; ++j) {
1276                 os << "<column"
1277                    << write_attribute("alignment", column_info[j].alignment)
1278                    << write_attribute("valignment", column_info[j].valignment)
1279                    << write_attribute("leftline", column_info[j].left_line)
1280                    << write_attribute("rightline", column_info[j].right_line)
1281                    << write_attribute("width", column_info[j].p_width.asString())
1282                    << write_attribute("special", column_info[j].align_special)
1283                    << ">\n";
1284         }
1285         for (row_type i = 0; i < rows_; ++i) {
1286                 os << "<row"
1287                    << write_attribute("topline", row_info[i].top_line)
1288                    << write_attribute("bottomline", row_info[i].bottom_line);
1289                 static const string def("default");
1290                 if (row_info[i].top_space_default)
1291                         os << write_attribute("topspace", def);
1292                 else
1293                         os << write_attribute("topspace", row_info[i].top_space);
1294                 if (row_info[i].bottom_space_default)
1295                         os << write_attribute("bottomspace", def);
1296                 else
1297                         os << write_attribute("bottomspace", row_info[i].bottom_space);
1298                 if (row_info[i].interline_space_default)
1299                         os << write_attribute("interlinespace", def);
1300                 else
1301                         os << write_attribute("interlinespace", row_info[i].interline_space);
1302                 os << write_attribute("endhead", row_info[i].endhead)
1303                    << write_attribute("endfirsthead", row_info[i].endfirsthead)
1304                    << write_attribute("endfoot", row_info[i].endfoot)
1305                    << write_attribute("endlastfoot", row_info[i].endlastfoot)
1306                    << write_attribute("newpage", row_info[i].newpage)
1307                    << ">\n";
1308                 for (col_type j = 0; j < columns_; ++j) {
1309                         os << "<cell"
1310                            << write_attribute("multicolumn", cell_info[i][j].multicolumn)
1311                            << write_attribute("alignment", cell_info[i][j].alignment)
1312                            << write_attribute("valignment", cell_info[i][j].valignment)
1313                            << write_attribute("topline", cell_info[i][j].top_line)
1314                            << write_attribute("bottomline", cell_info[i][j].bottom_line)
1315                            << write_attribute("leftline", cell_info[i][j].left_line)
1316                            << write_attribute("rightline", cell_info[i][j].right_line)
1317                            << write_attribute("rotate", cell_info[i][j].rotate)
1318                            << write_attribute("usebox", cell_info[i][j].usebox)
1319                            << write_attribute("width", cell_info[i][j].p_width)
1320                            << write_attribute("special", cell_info[i][j].align_special)
1321                            << ">\n";
1322                         os << "\\begin_inset ";
1323                         cell_info[i][j].inset->write(buf, os);
1324                         os << "\n\\end_inset\n"
1325                            << "</cell>\n";
1326                 }
1327                 os << "</row>\n";
1328         }
1329         os << "</lyxtabular>\n";
1330 }
1331
1332
1333 void LyXTabular::read(Buffer const & buf, LyXLex & lex)
1334 {
1335         string line;
1336         istream & is = lex.getStream();
1337
1338         l_getline(is, line);
1339         if (!prefixIs(line, "<lyxtabular ")
1340                 && !prefixIs(line, "<LyXTabular ")) {
1341                 BOOST_ASSERT(false);
1342                 return;
1343         }
1344
1345         int version;
1346         if (!getTokenValue(line, "version", version))
1347                 return;
1348         BOOST_ASSERT(version >= 2);
1349
1350         int rows_arg;
1351         if (!getTokenValue(line, "rows", rows_arg))
1352                 return;
1353         int columns_arg;
1354         if (!getTokenValue(line, "columns", columns_arg))
1355                 return;
1356         init(buf.params(), rows_arg, columns_arg);
1357         l_getline(is, line);
1358         if (!prefixIs(line, "<features")) {
1359                 lyxerr << "Wrong tabular format (expected <features ...> got"
1360                        << line << ')' << endl;
1361                 return;
1362         }
1363         getTokenValue(line, "rotate", rotate);
1364         getTokenValue(line, "booktabs", use_booktabs);
1365         getTokenValue(line, "islongtable", is_long_tabular);
1366         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1367         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1368         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1369         getTokenValue(line, "headTopDL", endhead.topDL);
1370         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1371         getTokenValue(line, "footTopDL", endfoot.topDL);
1372         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1373         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1374         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1375         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1376
1377         for (col_type j = 0; j < columns_; ++j) {
1378                 l_getline(is,line);
1379                 if (!prefixIs(line,"<column")) {
1380                         lyxerr << "Wrong tabular format (expected <column ...> got"
1381                                << line << ')' << endl;
1382                         return;
1383                 }
1384                 getTokenValue(line, "alignment", column_info[j].alignment);
1385                 getTokenValue(line, "valignment", column_info[j].valignment);
1386                 getTokenValue(line, "leftline", column_info[j].left_line);
1387                 getTokenValue(line, "rightline", column_info[j].right_line);
1388                 getTokenValue(line, "width", column_info[j].p_width);
1389                 getTokenValue(line, "special", column_info[j].align_special);
1390         }
1391
1392         for (row_type i = 0; i < rows_; ++i) {
1393                 l_getline(is, line);
1394                 if (!prefixIs(line, "<row")) {
1395                         lyxerr << "Wrong tabular format (expected <row ...> got"
1396                                << line << ')' << endl;
1397                         return;
1398                 }
1399                 getTokenValue(line, "topline", row_info[i].top_line);
1400                 getTokenValue(line, "bottomline", row_info[i].bottom_line);
1401                 getTokenValue(line, "topspace", row_info[i].top_space,
1402                               row_info[i].top_space_default);
1403                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1404                               row_info[i].bottom_space_default);
1405                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1406                               row_info[i].interline_space_default);
1407                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1408                 getTokenValue(line, "endhead", row_info[i].endhead);
1409                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1410                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1411                 getTokenValue(line, "newpage", row_info[i].newpage);
1412                 for (col_type j = 0; j < columns_; ++j) {
1413                         l_getline(is, line);
1414                         if (!prefixIs(line, "<cell")) {
1415                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1416                                        << line << ')' << endl;
1417                                 return;
1418                         }
1419                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1420                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1421                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1422                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1423                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1424                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1425                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1426                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1427                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1428                         getTokenValue(line, "width", cell_info[i][j].p_width);
1429                         getTokenValue(line, "special", cell_info[i][j].align_special);
1430                         l_getline(is, line);
1431                         if (prefixIs(line, "\\begin_inset")) {
1432                                 cell_info[i][j].inset->read(buf, lex);
1433                                 l_getline(is, line);
1434                         }
1435                         if (!prefixIs(line, "</cell>")) {
1436                                 lyxerr << "Wrong tabular format (expected </cell> got"
1437                                        << line << ')' << endl;
1438                                 return;
1439                         }
1440                 }
1441                 l_getline(is, line);
1442                 if (!prefixIs(line, "</row>")) {
1443                         lyxerr << "Wrong tabular format (expected </row> got"
1444                                << line << ')' << endl;
1445                         return;
1446                 }
1447         }
1448         while (!prefixIs(line, "</lyxtabular>")) {
1449                 l_getline(is, line);
1450         }
1451         set_row_column_number_info();
1452 }
1453
1454
1455 bool LyXTabular::isMultiColumn(idx_type cell) const
1456 {
1457         return cellinfo_of_cell(cell).multicolumn != LyXTabular::CELL_NORMAL;
1458 }
1459
1460
1461 bool LyXTabular::isMultiColumnReal(idx_type cell) const
1462 {
1463         return column_of_cell(cell) != right_column_of_cell(cell) &&
1464                         cellinfo_of_cell(cell).multicolumn != LyXTabular::CELL_NORMAL;
1465 }
1466
1467
1468 LyXTabular::cellstruct & LyXTabular::cellinfo_of_cell(idx_type cell) const
1469 {
1470         return cell_info[row_of_cell(cell)][column_of_cell(cell)];
1471 }
1472
1473
1474 void LyXTabular::setMultiColumn(Buffer * buffer, idx_type cell,
1475                                 idx_type number)
1476 {
1477         cellstruct & cs = cellinfo_of_cell(cell);
1478         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1479         cs.alignment = column_info[column_of_cell(cell)].alignment;
1480         cs.top_line = row_info[row_of_cell(cell)].top_line;
1481         cs.bottom_line = row_info[row_of_cell(cell)].bottom_line;
1482         cs.left_line = column_info[column_of_cell(cell)].left_line;
1483         cs.right_line = column_info[column_of_cell(cell+number-1)].right_line;
1484         for (idx_type i = 1; i < number; ++i) {
1485                 cellstruct & cs1 = cellinfo_of_cell(cell + i);
1486                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1487                 cs.inset->appendParagraphs(buffer, cs1.inset->paragraphs());
1488                 cs1.inset->clear();
1489         }
1490         set_row_column_number_info();
1491 }
1492
1493
1494 LyXTabular::idx_type LyXTabular::cells_in_multicolumn(idx_type cell) const
1495 {
1496         row_type const row = row_of_cell(cell);
1497         col_type column = column_of_cell(cell);
1498         idx_type result = 1;
1499         ++column;
1500         while (column < columns_ &&
1501                    cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
1502         {
1503                 ++result;
1504                 ++column;
1505         }
1506         return result;
1507 }
1508
1509
1510 LyXTabular::idx_type LyXTabular::unsetMultiColumn(idx_type cell)
1511 {
1512         row_type const row = row_of_cell(cell);
1513         col_type column = column_of_cell(cell);
1514
1515         idx_type result = 0;
1516
1517         if (cell_info[row][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN) {
1518                 cell_info[row][column].multicolumn = CELL_NORMAL;
1519                 ++column;
1520                 while (column < columns_ &&
1521                            cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
1522                 {
1523                         cell_info[row][column].multicolumn = CELL_NORMAL;
1524                         ++column;
1525                         ++result;
1526                 }
1527         }
1528         set_row_column_number_info();
1529         return result;
1530 }
1531
1532
1533 void LyXTabular::setBookTabs(bool what)
1534 {
1535         use_booktabs = what;
1536 }
1537
1538
1539 bool LyXTabular::useBookTabs() const
1540 {
1541         return use_booktabs;
1542 }
1543
1544
1545 void LyXTabular::setLongTabular(bool what)
1546 {
1547         is_long_tabular = what;
1548 }
1549
1550
1551 bool LyXTabular::isLongTabular() const
1552 {
1553         return is_long_tabular;
1554 }
1555
1556
1557 void LyXTabular::setRotateTabular(bool flag)
1558 {
1559         rotate = flag;
1560 }
1561
1562
1563 bool LyXTabular::getRotateTabular() const
1564 {
1565         return rotate;
1566 }
1567
1568
1569 void LyXTabular::setRotateCell(idx_type cell, bool flag)
1570 {
1571         cellinfo_of_cell(cell).rotate = flag;
1572 }
1573
1574
1575 bool LyXTabular::getRotateCell(idx_type cell) const
1576 {
1577         return cellinfo_of_cell(cell).rotate;
1578 }
1579
1580
1581 bool LyXTabular::needRotating() const
1582 {
1583         if (rotate)
1584                 return true;
1585         for (row_type i = 0; i < rows_; ++i)
1586                 for (col_type j = 0; j < columns_; ++j)
1587                         if (cell_info[i][j].rotate)
1588                                 return true;
1589         return false;
1590 }
1591
1592
1593 bool LyXTabular::isLastCell(idx_type cell) const
1594 {
1595         if (cell + 1 < numberofcells)
1596                 return false;
1597         return true;
1598 }
1599
1600
1601 LyXTabular::idx_type LyXTabular::getCellAbove(idx_type cell) const
1602 {
1603         if (row_of_cell(cell) > 0)
1604                 return cell_info[row_of_cell(cell)-1][column_of_cell(cell)].cellno;
1605         return cell;
1606 }
1607
1608
1609 LyXTabular::idx_type LyXTabular::getCellBelow(idx_type cell) const
1610 {
1611         if (row_of_cell(cell) + 1 < rows_)
1612                 return cell_info[row_of_cell(cell)+1][column_of_cell(cell)].cellno;
1613         return cell;
1614 }
1615
1616
1617 LyXTabular::idx_type LyXTabular::getLastCellAbove(idx_type cell) const
1618 {
1619         if (row_of_cell(cell) == 0)
1620                 return cell;
1621         if (!isMultiColumn(cell))
1622                 return getCellAbove(cell);
1623         return cell_info[row_of_cell(cell) - 1][right_column_of_cell(cell)].cellno;
1624 }
1625
1626
1627 LyXTabular::idx_type LyXTabular::getLastCellBelow(idx_type cell) const
1628 {
1629         if (row_of_cell(cell) + 1 >= rows_)
1630                 return cell;
1631         if (!isMultiColumn(cell))
1632                 return getCellBelow(cell);
1633         return cell_info[row_of_cell(cell) + 1][right_column_of_cell(cell)].cellno;
1634 }
1635
1636
1637 LyXTabular::idx_type LyXTabular::getCellNumber(row_type row,
1638                                                col_type column) const
1639 {
1640         BOOST_ASSERT(column != npos && column < columns_ &&
1641                      row    != npos && row    < rows_);
1642         return cell_info[row][column].cellno;
1643 }
1644
1645
1646 void LyXTabular::setUsebox(idx_type cell, BoxType type)
1647 {
1648         cellinfo_of_cell(cell).usebox = type;
1649 }
1650
1651
1652 LyXTabular::BoxType LyXTabular::getUsebox(idx_type cell) const
1653 {
1654         if (column_info[column_of_cell(cell)].p_width.zero() &&
1655                 !(isMultiColumn(cell) && !cellinfo_of_cell(cell).p_width.zero()))
1656                 return BOX_NONE;
1657         if (cellinfo_of_cell(cell).usebox > 1)
1658                 return cellinfo_of_cell(cell).usebox;
1659         return useParbox(cell);
1660 }
1661
1662
1663 ///
1664 //  This are functions used for the longtable support
1665 ///
1666 void LyXTabular::setLTHead(row_type row, bool flag, ltType const & hd,
1667                            bool first)
1668 {
1669         if (first) {
1670                 endfirsthead = hd;
1671                 if (hd.set)
1672                         row_info[row].endfirsthead = flag;
1673         } else {
1674                 endhead = hd;
1675                 if (hd.set)
1676                         row_info[row].endhead = flag;
1677         }
1678 }
1679
1680
1681 bool LyXTabular::getRowOfLTHead(row_type row, ltType & hd) const
1682 {
1683         hd = endhead;
1684         hd.set = haveLTHead();
1685         return row_info[row].endhead;
1686 }
1687
1688
1689 bool LyXTabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1690 {
1691         hd = endfirsthead;
1692         hd.set = haveLTFirstHead();
1693         return row_info[row].endfirsthead;
1694 }
1695
1696
1697 void LyXTabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1698                            bool last)
1699 {
1700         if (last) {
1701                 endlastfoot = fd;
1702                 if (fd.set)
1703                         row_info[row].endlastfoot = flag;
1704         } else {
1705                 endfoot = fd;
1706                 if (fd.set)
1707                         row_info[row].endfoot = flag;
1708         }
1709 }
1710
1711
1712 bool LyXTabular::getRowOfLTFoot(row_type row, ltType & fd) const
1713 {
1714         fd = endfoot;
1715         fd.set = haveLTFoot();
1716         return row_info[row].endfoot;
1717 }
1718
1719
1720 bool LyXTabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1721 {
1722         fd = endlastfoot;
1723         fd.set = haveLTLastFoot();
1724         return row_info[row].endlastfoot;
1725 }
1726
1727
1728 void LyXTabular::setLTNewPage(row_type row, bool what)
1729 {
1730         row_info[row].newpage = what;
1731 }
1732
1733
1734 bool LyXTabular::getLTNewPage(row_type row) const
1735 {
1736         return row_info[row].newpage;
1737 }
1738
1739
1740 bool LyXTabular::haveLTHead() const
1741 {
1742         for (row_type i = 0; i < rows_; ++i)
1743                 if (row_info[i].endhead)
1744                         return true;
1745         return false;
1746 }
1747
1748
1749 bool LyXTabular::haveLTFirstHead() const
1750 {
1751         if (endfirsthead.empty)
1752                 return false;
1753         for (row_type i = 0; i < rows_; ++i)
1754                 if (row_info[i].endfirsthead)
1755                         return true;
1756         return false;
1757 }
1758
1759
1760 bool LyXTabular::haveLTFoot() const
1761 {
1762         for (row_type i = 0; i < rows_; ++i)
1763                 if (row_info[i].endfoot)
1764                         return true;
1765         return false;
1766 }
1767
1768
1769 bool LyXTabular::haveLTLastFoot() const
1770 {
1771         if (endlastfoot.empty)
1772                 return false;
1773         for (row_type i = 0; i < rows_; ++i)
1774                 if (row_info[i].endlastfoot)
1775                         return true;
1776         return false;
1777 }
1778
1779
1780 // end longtable support functions
1781
1782 void LyXTabular::setAscentOfRow(row_type row, int height)
1783 {
1784         if (row >= rows_ || row_info[row].ascent_of_row == height)
1785                 return;
1786         row_info[row].ascent_of_row = height;
1787 }
1788
1789
1790 void LyXTabular::setDescentOfRow(row_type row, int height)
1791 {
1792         if (row >= rows_ || row_info[row].descent_of_row == height)
1793                 return;
1794         row_info[row].descent_of_row = height;
1795 }
1796
1797
1798 int LyXTabular::getAscentOfRow(row_type row) const
1799 {
1800         if (row >= rows_)
1801                 return 0;
1802         return row_info[row].ascent_of_row;
1803 }
1804
1805
1806 int LyXTabular::getDescentOfRow(row_type row) const
1807 {
1808         BOOST_ASSERT(row < rows_);
1809         return row_info[row].descent_of_row;
1810 }
1811
1812
1813 int LyXTabular::getHeightOfTabular() const
1814 {
1815         int height = 0;
1816         for (row_type row = 0; row < rows_; ++row)
1817                 height += getAscentOfRow(row) + getDescentOfRow(row) +
1818                         getAdditionalHeight(row);
1819         return height;
1820 }
1821
1822
1823 bool LyXTabular::isPartOfMultiColumn(row_type row, col_type column) const
1824 {
1825         BOOST_ASSERT(row < rows_);
1826         BOOST_ASSERT(column < columns_);
1827         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
1828 }
1829
1830
1831 int LyXTabular::TeXTopHLine(odocstream & os, row_type row) const
1832 {
1833         // FIXME: assert or return 0 as in TeXBottomHLine()?
1834         BOOST_ASSERT(row != npos);
1835         BOOST_ASSERT(row < rows_);
1836
1837         idx_type const fcell = getFirstCellInRow(row);
1838         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1839         idx_type tmp = 0;
1840
1841         for (idx_type i = fcell; i < n; ++i) {
1842                 if (topLine(i))
1843                         ++tmp;
1844         }
1845         if (use_booktabs && row == 0) {
1846                 os << "\\toprule ";
1847         } else if (tmp == n - fcell) {
1848                 os << (use_booktabs ? "\\midrule " : "\\hline ");
1849         } else if (tmp) {
1850                 for (idx_type i = fcell; i < n; ++i) {
1851                         if (topLine(i)) {
1852                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1853                                    << column_of_cell(i) + 1
1854                                    << '-'
1855                                    << right_column_of_cell(i) + 1
1856                                    << "} ";
1857                         }
1858                 }
1859         } else {
1860                 return 0;
1861         }
1862         os << "\n";
1863         return 1;
1864 }
1865
1866
1867 int LyXTabular::TeXBottomHLine(odocstream & os, row_type row) const
1868 {
1869         // FIXME: return 0 or assert as in TeXTopHLine()?
1870         if (row == npos || row >= rows_)
1871                 return 0;
1872
1873         idx_type const fcell = getFirstCellInRow(row);
1874         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1875         idx_type tmp = 0;
1876
1877         for (idx_type i = fcell; i < n; ++i) {
1878                 if (bottomLine(i))
1879                         ++tmp;
1880         }
1881         if (use_booktabs && row == rows_ - 1) {
1882                 os << "\\bottomrule";
1883         } else if (tmp == n - fcell) {
1884                 os << (use_booktabs ? "\\midrule" : "\\hline");
1885         } else if (tmp) {
1886                 for (idx_type i = fcell; i < n; ++i) {
1887                         if (bottomLine(i)) {
1888                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1889                                    << column_of_cell(i) + 1
1890                                    << '-'
1891                                    << right_column_of_cell(i) + 1
1892                                    << "} ";
1893                         }
1894                 }
1895         } else {
1896                 return 0;
1897         }
1898         os << "\n";
1899         return 1;
1900 }
1901
1902
1903 int LyXTabular::TeXCellPreamble(odocstream & os, idx_type cell) const
1904 {
1905         int ret = 0;
1906
1907         if (getRotateCell(cell)) {
1908                 os << "\\begin{sideways}\n";
1909                 ++ret;
1910         }
1911         if (isMultiColumn(cell)) {
1912                 os << "\\multicolumn{" << cells_in_multicolumn(cell) << "}{";
1913                 if (!cellinfo_of_cell(cell).align_special.empty()) {
1914                         os << lyx::from_ascii(cellinfo_of_cell(cell).align_special)
1915                            << "}{";
1916                 } else {
1917                         if (leftLine(cell) &&
1918                                 (isFirstCellInRow(cell) ||
1919                                  (!isMultiColumn(cell - 1) && !leftLine(cell, true) &&
1920                                   !rightLine(cell - 1, true))))
1921                         {
1922                                 os << '|';
1923                         }
1924                         if (!getPWidth(cell).zero()) {
1925                                 switch (getVAlignment(cell)) {
1926                                 case LYX_VALIGN_TOP:
1927                                         os << 'p';
1928                                         break;
1929                                 case LYX_VALIGN_MIDDLE:
1930                                         os << 'm';
1931                                         break;
1932                                 case LYX_VALIGN_BOTTOM:
1933                                         os << 'b';
1934                                         break;
1935                                 }
1936                                 os << '{'
1937                                    << lyx::from_ascii(getPWidth(cell).asLatexString())
1938                                    << '}';
1939                         } else {
1940                                 switch (getAlignment(cell)) {
1941                                 case LYX_ALIGN_LEFT:
1942                                         os << 'l';
1943                                         break;
1944                                 case LYX_ALIGN_RIGHT:
1945                                         os << 'r';
1946                                         break;
1947                                 default:
1948                                         os << 'c';
1949                                         break;
1950                                 }
1951                         }
1952                         if (rightLine(cell))
1953                                 os << '|';
1954                         if (((cell + 1) < numberofcells) && !isFirstCellInRow(cell+1) &&
1955                                 leftLine(cell+1))
1956                                 os << '|';
1957                         os << "}{";
1958                 }
1959         }
1960         if (getUsebox(cell) == BOX_PARBOX) {
1961                 os << "\\parbox[";
1962                 switch (getVAlignment(cell)) {
1963                 case LYX_VALIGN_TOP:
1964                         os << 't';
1965                         break;
1966                 case LYX_VALIGN_MIDDLE:
1967                         os << 'c';
1968                         break;
1969                 case LYX_VALIGN_BOTTOM:
1970                         os << 'b';
1971                         break;
1972                 }
1973                 os << "]{" << lyx::from_ascii(getPWidth(cell).asLatexString())
1974                    << "}{";
1975         } else if (getUsebox(cell) == BOX_MINIPAGE) {
1976                 os << "\\begin{minipage}[";
1977                 switch (getVAlignment(cell)) {
1978                 case LYX_VALIGN_TOP:
1979                         os << 't';
1980                         break;
1981                 case LYX_VALIGN_MIDDLE:
1982                         os << 'm';
1983                         break;
1984                 case LYX_VALIGN_BOTTOM:
1985                         os << 'b';
1986                         break;
1987                 }
1988                 os << "]{" << lyx::from_ascii(getPWidth(cell).asLatexString())
1989                    << "}\n";
1990                 ++ret;
1991         }
1992         return ret;
1993 }
1994
1995
1996 int LyXTabular::TeXCellPostamble(odocstream & os, idx_type cell) const
1997 {
1998         int ret = 0;
1999
2000         // usual cells
2001         if (getUsebox(cell) == BOX_PARBOX)
2002                 os << '}';
2003         else if (getUsebox(cell) == BOX_MINIPAGE) {
2004                 os << "%\n\\end{minipage}";
2005                 ret += 2;
2006         }
2007         if (isMultiColumn(cell)) {
2008                 os << '}';
2009         }
2010         if (getRotateCell(cell)) {
2011                 os << "%\n\\end{sideways}";
2012                 ++ret;
2013         }
2014         return ret;
2015 }
2016
2017
2018 int LyXTabular::TeXLongtableHeaderFooter(odocstream & os, Buffer const & buf,
2019                                          OutputParams const & runparams) const
2020 {
2021         if (!is_long_tabular)
2022                 return 0;
2023
2024         int ret = 0;
2025         // output header info
2026         if (haveLTHead()) {
2027                 if (endhead.topDL) {
2028                         os << "\\hline\n";
2029                         ++ret;
2030                 }
2031                 for (row_type i = 0; i < rows_; ++i) {
2032                         if (row_info[i].endhead) {
2033                                 ret += TeXRow(os, i, buf, runparams);
2034                         }
2035                 }
2036                 if (endhead.bottomDL) {
2037                         os << "\\hline\n";
2038                         ++ret;
2039                 }
2040                 os << "\\endhead\n";
2041                 ++ret;
2042                 if (endfirsthead.empty) {
2043                         os << "\\endfirsthead\n";
2044                         ++ret;
2045                 }
2046         }
2047         // output firstheader info
2048         if (haveLTFirstHead()) {
2049                 if (endfirsthead.topDL) {
2050                         os << "\\hline\n";
2051                         ++ret;
2052                 }
2053                 for (row_type i = 0; i < rows_; ++i) {
2054                         if (row_info[i].endfirsthead) {
2055                                 ret += TeXRow(os, i, buf, runparams);
2056                         }
2057                 }
2058                 if (endfirsthead.bottomDL) {
2059                         os << "\\hline\n";
2060                         ++ret;
2061                 }
2062                 os << "\\endfirsthead\n";
2063                 ++ret;
2064         }
2065         // output footer info
2066         if (haveLTFoot()) {
2067                 if (endfoot.topDL) {
2068                         os << "\\hline\n";
2069                         ++ret;
2070                 }
2071                 for (row_type i = 0; i < rows_; ++i) {
2072                         if (row_info[i].endfoot) {
2073                                 ret += TeXRow(os, i, buf, runparams);
2074                         }
2075                 }
2076                 if (endfoot.bottomDL) {
2077                         os << "\\hline\n";
2078                         ++ret;
2079                 }
2080                 os << "\\endfoot\n";
2081                 ++ret;
2082                 if (endlastfoot.empty) {
2083                         os << "\\endlastfoot\n";
2084                         ++ret;
2085                 }
2086         }
2087         // output lastfooter info
2088         if (haveLTLastFoot()) {
2089                 if (endlastfoot.topDL) {
2090                         os << "\\hline\n";
2091                         ++ret;
2092                 }
2093                 for (row_type i = 0; i < rows_; ++i) {
2094                         if (row_info[i].endlastfoot) {
2095                                 ret += TeXRow(os, i, buf, runparams);
2096                         }
2097                 }
2098                 if (endlastfoot.bottomDL) {
2099                         os << "\\hline\n";
2100                         ++ret;
2101                 }
2102                 os << "\\endlastfoot\n";
2103                 ++ret;
2104         }
2105         return ret;
2106 }
2107
2108
2109 bool LyXTabular::isValidRow(row_type row) const
2110 {
2111         if (!is_long_tabular)
2112                 return true;
2113         return !row_info[row].endhead && !row_info[row].endfirsthead &&
2114                         !row_info[row].endfoot && !row_info[row].endlastfoot;
2115 }
2116
2117
2118 int LyXTabular::TeXRow(odocstream & os, row_type i, Buffer const & buf,
2119                        OutputParams const & runparams) const
2120 {
2121         idx_type cell = getCellNumber(i, 0);
2122         int ret = TeXTopHLine(os, i);
2123         if (row_info[i].top_space_default) {
2124                 if (use_booktabs)
2125                         os << "\\addlinespace\n";
2126                 else
2127                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2128         } else if(!row_info[i].top_space.zero()) {
2129                 if (use_booktabs)
2130                         os << "\\addlinespace["
2131                            << lyx::from_ascii(row_info[i].top_space.asLatexString())
2132                            << "]\n";
2133                 else {
2134                         os << "\\noalign{\\vskip"
2135                            << lyx::from_ascii(row_info[i].top_space.asLatexString())
2136                            << "}\n";
2137                 }
2138                 ++ret;
2139         }
2140         
2141         for (col_type j = 0; j < columns_; ++j) {
2142                 if (isPartOfMultiColumn(i, j))
2143                         continue;
2144                 ret += TeXCellPreamble(os, cell);
2145                 shared_ptr<InsetText> inset = getCellInset(cell);
2146
2147                 Paragraph const & par = inset->paragraphs().front();
2148                 bool rtl = par.isRightToLeftPar(buf.params())
2149                         && !par.empty()
2150                         && getPWidth(cell).zero();
2151
2152                 if (rtl)
2153                         os << "\\R{";
2154                 ret += inset->latex(buf, os, runparams);
2155                 if (rtl)
2156                         os << '}';
2157
2158                 ret += TeXCellPostamble(os, cell);
2159                 if (!isLastCellInRow(cell)) { // not last cell in row
2160                         os << "&\n";
2161                         ++ret;
2162                 }
2163                 ++cell;
2164         }
2165         os << "\\tabularnewline";
2166         if (row_info[i].bottom_space_default) {
2167                 if (use_booktabs)
2168                         os << "\\addlinespace";
2169                 else
2170                         os << "[\\doublerulesep]";
2171         } else if (!row_info[i].bottom_space.zero()) {
2172                 if (use_booktabs)
2173                         os << "\\addlinespace";
2174                 os << '['
2175                    << lyx::from_ascii(row_info[i].bottom_space.asLatexString())
2176                    << ']';
2177         }
2178         os << '\n';
2179         ++ret;
2180         ret += TeXBottomHLine(os, i);
2181         if (row_info[i].interline_space_default) {
2182                 if (use_booktabs)
2183                         os << "\\addlinespace\n";
2184                 else
2185                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2186         } else if (!row_info[i].interline_space.zero()) {
2187                 if (use_booktabs)
2188                         os << "\\addlinespace["
2189                            << lyx::from_ascii(row_info[i].interline_space.asLatexString())
2190                            << "]\n";
2191                 else
2192                         os << "\\noalign{\\vskip"
2193                            << lyx::from_ascii(row_info[i].interline_space.asLatexString())
2194                            << "}\n";
2195                 ++ret;
2196         }
2197         return ret;
2198 }
2199
2200
2201 int LyXTabular::latex(Buffer const & buf, odocstream & os,
2202                       OutputParams const & runparams) const
2203 {
2204         int ret = 0;
2205
2206         //+---------------------------------------------------------------------
2207         //+                      first the opening preamble                    +
2208         //+---------------------------------------------------------------------
2209
2210         if (rotate) {
2211                 os << "\\begin{sideways}\n";
2212                 ++ret;
2213         }
2214         if (is_long_tabular)
2215                 os << "\\begin{longtable}{";
2216         else
2217                 os << "\\begin{tabular}{";
2218         for (col_type i = 0; i < columns_; ++i) {
2219                 if (!column_info[i].align_special.empty()) {
2220                         os << lyx::from_ascii(column_info[i].align_special);
2221                 } else {
2222                         if (!use_booktabs && column_info[i].left_line)
2223                                 os << '|';
2224                         if (!column_info[i].p_width.zero()) {
2225                                 switch (column_info[i].alignment) {
2226                                 case LYX_ALIGN_LEFT:
2227                                         os << ">{\\raggedright}";
2228                                         break;
2229                                 case LYX_ALIGN_RIGHT:
2230                                         os << ">{\\raggedleft}";
2231                                         break;
2232                                 case LYX_ALIGN_CENTER:
2233                                         os << ">{\\centering}";
2234                                         break;
2235                                 case LYX_ALIGN_NONE:
2236                                 case LYX_ALIGN_BLOCK:
2237                                 case LYX_ALIGN_LAYOUT:
2238                                 case LYX_ALIGN_SPECIAL:
2239                                         break;
2240                                 }
2241
2242                                 switch (column_info[i].valignment) {
2243                                 case LYX_VALIGN_TOP:
2244                                         os << 'p';
2245                                         break;
2246                                 case LYX_VALIGN_MIDDLE:
2247                                         os << 'm';
2248                                         break;
2249                                 case LYX_VALIGN_BOTTOM:
2250                                         os << 'b';
2251                                         break;
2252                         }
2253                                 os << '{'
2254                                    << lyx::from_ascii(column_info[i].p_width.asLatexString())
2255                                    << '}';
2256                         } else {
2257                                 switch (column_info[i].alignment) {
2258                                 case LYX_ALIGN_LEFT:
2259                                         os << 'l';
2260                                         break;
2261                                 case LYX_ALIGN_RIGHT:
2262                                         os << 'r';
2263                                         break;
2264                                 default:
2265                                         os << 'c';
2266                                         break;
2267                                 }
2268                         }
2269                         if (!use_booktabs && column_info[i].right_line)
2270                                 os << '|';
2271                 }
2272         }
2273         os << "}\n";
2274         ++ret;
2275
2276         ret += TeXLongtableHeaderFooter(os, buf, runparams);
2277
2278         //+---------------------------------------------------------------------
2279         //+                      the single row and columns (cells)            +
2280         //+---------------------------------------------------------------------
2281
2282         for (row_type i = 0; i < rows_; ++i) {
2283                 if (isValidRow(i)) {
2284                         ret += TeXRow(os, i, buf, runparams);
2285                         if (is_long_tabular && row_info[i].newpage) {
2286                                 os << "\\newpage\n";
2287                                 ++ret;
2288                         }
2289                 }
2290         }
2291
2292         //+---------------------------------------------------------------------
2293         //+                      the closing of the tabular                    +
2294         //+---------------------------------------------------------------------
2295
2296         if (is_long_tabular)
2297                 os << "\\end{longtable}";
2298         else
2299                 os << "\\end{tabular}";
2300         if (rotate) {
2301                 os << "\n\\end{sideways}";
2302                 ++ret;
2303         }
2304
2305         return ret;
2306 }
2307
2308
2309 int LyXTabular::docbookRow(Buffer const & buf, ostream & os, row_type row,
2310                            OutputParams const & runparams) const
2311 {
2312         int ret = 0;
2313         idx_type cell = getFirstCellInRow(row);
2314
2315         os << "<row>\n";
2316         for (col_type j = 0; j < columns_; ++j) {
2317                 if (isPartOfMultiColumn(row, j))
2318                         continue;
2319
2320                 os << "<entry align=\"";
2321                 switch (getAlignment(cell)) {
2322                 case LYX_ALIGN_LEFT:
2323                         os << "left";
2324                         break;
2325                 case LYX_ALIGN_RIGHT:
2326                         os << "right";
2327                         break;
2328                 default:
2329                         os << "center";
2330                         break;
2331                 }
2332
2333                 os << "\" valign=\"";
2334                 switch (getVAlignment(cell)) {
2335                 case LYX_VALIGN_TOP:
2336                         os << "top";
2337                         break;
2338                 case LYX_VALIGN_BOTTOM:
2339                         os << "bottom";
2340                         break;
2341                 case LYX_VALIGN_MIDDLE:
2342                         os << "middle";
2343                 }
2344                 os << '"';
2345
2346                 if (isMultiColumn(cell)) {
2347                         os << " namest=\"col" << j << "\" ";
2348                         os << "nameend=\"col" << j + cells_in_multicolumn(cell) - 1<< '"';
2349                 }
2350
2351                 os << '>';
2352                 ret += getCellInset(cell)->docbook(buf, os, runparams);
2353                 os << "</entry>\n";
2354                 ++cell;
2355         }
2356         os << "</row>\n";
2357         return ret;
2358 }
2359
2360
2361 int LyXTabular::docbook(Buffer const & buf, ostream & os,
2362                         OutputParams const & runparams) const
2363 {
2364         int ret = 0;
2365
2366         //+---------------------------------------------------------------------
2367         //+                      first the opening preamble                    +
2368         //+---------------------------------------------------------------------
2369
2370         os << "<tgroup cols=\"" << columns_
2371            << "\" colsep=\"1\" rowsep=\"1\">\n";
2372
2373         for (col_type i = 0; i < columns_; ++i) {
2374                 os << "<colspec colname=\"col" << i << "\" align=\"";
2375                 switch (column_info[i].alignment) {
2376                 case LYX_ALIGN_LEFT:
2377                         os << "left";
2378                         break;
2379                 case LYX_ALIGN_RIGHT:
2380                         os << "right";
2381                         break;
2382                 default:
2383                         os << "center";
2384                         break;
2385                 }
2386                 os << '"';
2387                 if (runparams.flavor == OutputParams::XML)
2388                         os << '/';
2389                 os << ">\n";
2390                 ++ret;
2391         }
2392
2393         //+---------------------------------------------------------------------
2394         //+                      Long Tabular case                             +
2395         //+---------------------------------------------------------------------
2396
2397         // output header info
2398         if (haveLTHead() || haveLTFirstHead()) {
2399                 os << "<thead>\n";
2400                 ++ret;
2401                 for (row_type i = 0; i < rows_; ++i) {
2402                         if (row_info[i].endhead || row_info[i].endfirsthead) {
2403                                 ret += docbookRow(buf, os, i, runparams);
2404                         }
2405                 }
2406                 os << "</thead>\n";
2407                 ++ret;
2408         }
2409         // output footer info
2410         if (haveLTFoot() || haveLTLastFoot()) {
2411                 os << "<tfoot>\n";
2412                 ++ret;
2413                 for (row_type i = 0; i < rows_; ++i) {
2414                         if (row_info[i].endfoot || row_info[i].endlastfoot) {
2415                                 ret += docbookRow(buf, os, i, runparams);
2416                         }
2417                 }
2418                 os << "</tfoot>\n";
2419                 ++ret;
2420         }
2421
2422         //+---------------------------------------------------------------------
2423         //+                      the single row and columns (cells)            +
2424         //+---------------------------------------------------------------------
2425
2426         os << "<tbody>\n";
2427         ++ret;
2428         for (row_type i = 0; i < rows_; ++i) {
2429                 if (isValidRow(i)) {
2430                         ret += docbookRow(buf, os, i, runparams);
2431                 }
2432         }
2433         os << "</tbody>\n";
2434         ++ret;
2435         //+---------------------------------------------------------------------
2436         //+                      the closing of the tabular                    +
2437         //+---------------------------------------------------------------------
2438
2439         os << "</tgroup>";
2440         ++ret;
2441
2442         return ret;
2443 }
2444
2445
2446 int LyXTabular::asciiTopHLine(lyx::odocstream & os, row_type row,
2447                               vector<unsigned int> const & clen) const
2448 {
2449         idx_type const fcell = getFirstCellInRow(row);
2450         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2451         idx_type tmp = 0;
2452
2453         for (idx_type i = fcell; i < n; ++i) {
2454                 if (topLine(i)) {
2455                         ++tmp;
2456                         break;
2457                 }
2458         }
2459         if (!tmp)
2460                 return 0;
2461
2462         lyx::char_type ch;
2463         for (idx_type i = fcell; i < n; ++i) {
2464                 if (topLine(i)) {
2465                         if (leftLine(i))
2466                                 os << "+-";
2467                         else
2468                                 os << "--";
2469                         ch = '-';
2470                 } else {
2471                         os << "  ";
2472                         ch = ' ';
2473                 }
2474                 col_type column = column_of_cell(i);
2475                 int len = clen[column];
2476                 while (column < columns_ - 1
2477                        && isPartOfMultiColumn(row, ++column))
2478                         len += clen[column] + 4;
2479                 os << docstring(len, ch);
2480                 if (topLine(i)) {
2481                         if (rightLine(i))
2482                                 os << "-+";
2483                         else
2484                                 os << "--";
2485                 } else {
2486                         os << "  ";
2487                 }
2488         }
2489         os << endl;
2490         return 1;
2491 }
2492
2493
2494 int LyXTabular::asciiBottomHLine(lyx::odocstream & os, row_type row,
2495                                  vector<unsigned int> const & clen) const
2496 {
2497         idx_type const fcell = getFirstCellInRow(row);
2498         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2499         idx_type tmp = 0;
2500
2501         for (idx_type i = fcell; i < n; ++i) {
2502                 if (bottomLine(i)) {
2503                         ++tmp;
2504                         break;
2505                 }
2506         }
2507         if (!tmp)
2508                 return 0;
2509
2510         lyx::char_type ch;
2511         for (idx_type i = fcell; i < n; ++i) {
2512                 if (bottomLine(i)) {
2513                         if (leftLine(i))
2514                                 os << "+-";
2515                         else
2516                                 os << "--";
2517                         ch = '-';
2518                 } else {
2519                         os << "  ";
2520                         ch = ' ';
2521                 }
2522                 col_type column = column_of_cell(i);
2523                 int len = clen[column];
2524                 while (column < columns_ -1
2525                        && isPartOfMultiColumn(row, ++column))
2526                         len += clen[column] + 4;
2527                 os << docstring(len, ch);
2528                 if (bottomLine(i)) {
2529                         if (rightLine(i))
2530                                 os << "-+";
2531                         else
2532                                 os << "--";
2533                 } else {
2534                         os << "  ";
2535                 }
2536         }
2537         os << endl;
2538         return 1;
2539 }
2540
2541
2542 int LyXTabular::asciiPrintCell(Buffer const & buf, lyx::odocstream & os,
2543                                OutputParams const & runparams,
2544                                idx_type cell, row_type row, col_type column,
2545                                vector<unsigned int> const & clen,
2546                                bool onlydata) const
2547 {
2548         lyx::odocstringstream sstr;
2549         int const ret = getCellInset(cell)->plaintext(buf, sstr, runparams);
2550
2551         if (onlydata) {
2552                 os << sstr.str();
2553                 return ret;
2554         }
2555
2556         if (leftLine(cell))
2557                 os << "| ";
2558         else
2559                 os << "  ";
2560
2561         unsigned int len1 = sstr.str().length();
2562         unsigned int len2 = clen[column];
2563         while (column < columns_ -1
2564                && isPartOfMultiColumn(row, ++column))
2565                 len2 += clen[column] + 4;
2566         len2 -= len1;
2567
2568         switch (getAlignment(cell)) {
2569         default:
2570         case LYX_ALIGN_LEFT:
2571                 len1 = 0;
2572                 break;
2573         case LYX_ALIGN_RIGHT:
2574                 len1 = len2;
2575                 len2 = 0;
2576                 break;
2577         case LYX_ALIGN_CENTER:
2578                 len1 = len2 / 2;
2579                 len2 -= len1;
2580                 break;
2581         }
2582
2583         os << docstring(len1, ' ') << sstr.str()
2584            << docstring(len2, ' ');
2585
2586         if (rightLine(cell))
2587                 os << " |";
2588         else
2589                 os << "  ";
2590
2591         return ret;
2592 }
2593
2594
2595 int LyXTabular::plaintext(Buffer const & buf, lyx::odocstream & os,
2596                       OutputParams const & runparams,
2597                       int const depth,
2598                       bool onlydata, unsigned char delim) const
2599 {
2600         int ret = 0;
2601
2602         // first calculate the width of the single columns
2603         vector<unsigned int> clen(columns_);
2604
2605         if (!onlydata) {
2606                 // first all non (real) multicolumn cells!
2607                 for (col_type j = 0; j < columns_; ++j) {
2608                         clen[j] = 0;
2609                         for (row_type i = 0; i < rows_; ++i) {
2610                                 idx_type cell = getCellNumber(i, j);
2611                                 if (isMultiColumnReal(cell))
2612                                         continue;
2613                                 lyx::odocstringstream sstr;
2614                                 getCellInset(cell)->plaintext(buf, sstr, runparams);
2615                                 if (clen[j] < sstr.str().length())
2616                                         clen[j] = sstr.str().length();
2617                         }
2618                 }
2619                 // then all (real) multicolumn cells!
2620                 for (col_type j = 0; j < columns_; ++j) {
2621                         for (row_type i = 0; i < rows_; ++i) {
2622                                 idx_type cell = getCellNumber(i, j);
2623                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2624                                         continue;
2625                                 lyx::odocstringstream sstr;
2626                                 getCellInset(cell)->plaintext(buf, sstr, runparams);
2627                                 int len = int(sstr.str().length());
2628                                 idx_type const n = cells_in_multicolumn(cell);
2629                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2630                                         len -= clen[k];
2631                                 if (len > int(clen[j + n - 1]))
2632                                         clen[j + n - 1] = len;
2633                         }
2634                 }
2635         }
2636         idx_type cell = 0;
2637         for (row_type i = 0; i < rows_; ++i) {
2638                 if (!onlydata && asciiTopHLine(os, i, clen))
2639                         os << docstring(depth * 2, ' ');
2640                 for (col_type j = 0; j < columns_; ++j) {
2641                         if (isPartOfMultiColumn(i, j))
2642                                 continue;
2643                         if (onlydata && j > 0)
2644                                 os << delim;
2645                         ret += asciiPrintCell(buf, os, runparams,
2646                                               cell, i, j, clen, onlydata);
2647                         ++cell;
2648                 }
2649                 os << endl;
2650                 if (!onlydata) {
2651                         os << docstring(depth * 2, ' ');
2652                         if (asciiBottomHLine(os, i, clen))
2653                                 os << docstring(depth * 2, ' ');
2654                 }
2655         }
2656         return ret;
2657 }
2658
2659
2660 shared_ptr<InsetText> LyXTabular::getCellInset(idx_type cell) const
2661 {
2662         return cell_info[row_of_cell(cell)][column_of_cell(cell)].inset;
2663 }
2664
2665
2666 shared_ptr<InsetText> LyXTabular::getCellInset(row_type row,
2667                                                col_type column) const
2668 {
2669         return cell_info[row][column].inset;
2670 }
2671
2672
2673 void LyXTabular::setCellInset(row_type row, col_type column,
2674                               shared_ptr<InsetText> ins) const
2675 {
2676         cell_info[row][column].inset = ins;
2677 }
2678
2679
2680 LyXTabular::idx_type
2681 LyXTabular::getCellFromInset(InsetBase const * inset) const
2682 {
2683         // is this inset part of the tabular?
2684         if (!inset) {
2685                 lyxerr << "Error: this is not a cell of the tabular!" << endl;
2686                 BOOST_ASSERT(false);
2687         }
2688
2689         for (idx_type cell = 0, n = getNumberOfCells(); cell < n; ++cell)
2690                 if (getCellInset(cell).get() == inset) {
2691                         lyxerr[Debug::INSETTEXT] << "LyXTabular::getCellFromInset: "
2692                                 << "cell=" << cell << endl;
2693                         return cell;
2694                 }
2695
2696         // We should have found a cell at this point
2697         lyxerr << "LyXTabular::getCellFromInset: Cell of inset "
2698                 << inset << " not found!" << endl;
2699         BOOST_ASSERT(false);
2700         // shut up compiler
2701         return 0;
2702 }
2703
2704
2705 void LyXTabular::validate(LaTeXFeatures & features) const
2706 {
2707         features.require("NeedTabularnewline");
2708         if (useBookTabs())
2709                 features.require("booktabs");
2710         if (isLongTabular())
2711                 features.require("longtable");
2712         if (needRotating())
2713                 features.require("rotating");
2714         for (idx_type cell = 0; cell < numberofcells; ++cell) {
2715                 if (getVAlignment(cell) != LYX_VALIGN_TOP ||
2716                      (!getPWidth(cell).zero() && !isMultiColumn(cell)))
2717                         features.require("array");
2718                 getCellInset(cell)->validate(features);
2719         }
2720 }
2721
2722
2723 LyXTabular::BoxType LyXTabular::useParbox(idx_type cell) const
2724 {
2725         ParagraphList const & parlist = getCellInset(cell)->paragraphs();
2726         ParagraphList::const_iterator cit = parlist.begin();
2727         ParagraphList::const_iterator end = parlist.end();
2728
2729         for (; cit != end; ++cit)
2730                 for (int i = 0; i < cit->size(); ++i)
2731                         if (cit->isNewline(i))
2732                                 return BOX_PARBOX;
2733
2734         return BOX_NONE;
2735 }