]> git.lyx.org Git - lyx.git/blob - src/tabular.C
* Painter.h:
[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
41 namespace lyx {
42
43 using support::prefixIs;
44 using support::ltrim;
45 using support::rtrim;
46 using support::suffixIs;
47
48 using boost::shared_ptr;
49 using boost::dynamic_pointer_cast;
50
51 using std::abs;
52 using std::endl;
53 using std::getline;
54 using std::max;
55
56 using std::istream;
57 using std::ostream;
58 using std::ostringstream;
59 using std::vector;
60 using std::string;
61
62 #ifndef CXX_GLOBAL_CSTD
63 using std::strlen;
64 #endif
65
66
67 namespace {
68
69 int const WIDTH_OF_LINE = 5;
70 int const default_line_space = 10;
71
72
73 template <class T>
74 string const write_attribute(string const & name, T const & t)
75 {
76         string const s = tostr(t);
77         return s.empty() ? s : " " + name + "=\"" + s + "\"";
78 }
79
80 template <>
81 string const write_attribute(string const & name, string const & t)
82 {
83         return t.empty() ? t : " " + name + "=\"" + t + "\"";
84 }
85
86
87 template <>
88 string const write_attribute(string const & name, bool const & b)
89 {
90         // we write only true attribute values so we remove a bit of the
91         // file format bloat for tabulars.
92         return b ? write_attribute(name, convert<string>(b)) : string();
93 }
94
95
96 template <>
97 string const write_attribute(string const & name, int const & i)
98 {
99         // we write only true attribute values so we remove a bit of the
100         // file format bloat for tabulars.
101         return i ? write_attribute(name, convert<string>(i)) : string();
102 }
103
104
105 template <>
106 string const write_attribute(string const & name, LyXTabular::idx_type const & i)
107 {
108         // we write only true attribute values so we remove a bit of the
109         // file format bloat for tabulars.
110         return i ? write_attribute(name, convert<string>(i)) : string();
111 }
112
113
114 template <>
115 string const write_attribute(string const & name, LyXLength const & value)
116 {
117         // we write only the value if we really have one same reson as above.
118         return value.zero() ? string() : write_attribute(name, value.asString());
119 }
120
121
122 string const tostr(LyXAlignment const & num)
123 {
124         switch (num) {
125         case LYX_ALIGN_NONE:
126                 return "none";
127         case LYX_ALIGN_BLOCK:
128                 return "block";
129         case LYX_ALIGN_LEFT:
130                 return "left";
131         case LYX_ALIGN_CENTER:
132                 return "center";
133         case LYX_ALIGN_RIGHT:
134                 return "right";
135         case LYX_ALIGN_LAYOUT:
136                 return "layout";
137         case LYX_ALIGN_SPECIAL:
138                 return "special";
139         }
140         return string();
141 }
142
143
144 string const tostr(LyXTabular::VAlignment const & num)
145 {
146         switch (num) {
147         case LyXTabular::LYX_VALIGN_TOP:
148                 return "top";
149         case LyXTabular::LYX_VALIGN_MIDDLE:
150                 return "middle";
151         case LyXTabular::LYX_VALIGN_BOTTOM:
152                 return "bottom";
153         }
154         return string();
155 }
156
157
158 string const tostr(LyXTabular::BoxType const & num)
159 {
160         switch (num) {
161         case LyXTabular::BOX_NONE:
162                 return "none";
163         case LyXTabular::BOX_PARBOX:
164                 return "parbox";
165         case LyXTabular::BOX_MINIPAGE:
166                 return "minipage";
167         }
168         return string();
169 }
170
171
172 // I would have liked a fromstr template a lot better. (Lgb)
173 bool string2type(string const str, LyXAlignment & num)
174 {
175         if (str == "none")
176                 num = LYX_ALIGN_NONE;
177         else if (str == "block")
178                 num = LYX_ALIGN_BLOCK;
179         else if (str == "left")
180                 num = LYX_ALIGN_LEFT;
181         else if (str == "center")
182                 num = LYX_ALIGN_CENTER;
183         else if (str == "right")
184                 num = LYX_ALIGN_RIGHT;
185         else
186                 return false;
187         return true;
188 }
189
190
191 bool string2type(string const str, LyXTabular::VAlignment & num)
192 {
193         if (str == "top")
194                 num = LyXTabular::LYX_VALIGN_TOP;
195         else if (str == "middle" )
196                 num = LyXTabular::LYX_VALIGN_MIDDLE;
197         else if (str == "bottom")
198                 num = LyXTabular::LYX_VALIGN_BOTTOM;
199         else
200                 return false;
201         return true;
202 }
203
204
205 bool string2type(string const str, LyXTabular::BoxType & num)
206 {
207         if (str == "none")
208                 num = LyXTabular::BOX_NONE;
209         else if (str == "parbox")
210                 num = LyXTabular::BOX_PARBOX;
211         else if (str == "minipage")
212                 num = LyXTabular::BOX_MINIPAGE;
213         else
214                 return false;
215         return true;
216 }
217
218
219 bool string2type(string const str, bool & num)
220 {
221         if (str == "true")
222                 num = true;
223         else if (str == "false")
224                 num = false;
225         else
226                 return false;
227         return true;
228 }
229
230
231 bool getTokenValue(string const & str, char const * token, string & ret)
232 {
233         ret.erase();
234         size_t token_length = strlen(token);
235         string::size_type pos = str.find(token);
236
237         if (pos == string::npos || pos + token_length + 1 >= str.length()
238                 || str[pos + token_length] != '=')
239                 return false;
240         pos += token_length + 1;
241         char ch = str[pos];
242         if (ch != '"' && ch != '\'') { // only read till next space
243                 ret += ch;
244                 ch = ' ';
245         }
246         while (pos < str.length() - 1 && str[++pos] != ch)
247                 ret += str[pos];
248
249         return true;
250 }
251
252
253 bool getTokenValue(string const & str, char const * token, int & num)
254 {
255         string tmp;
256         num = 0;
257         if (!getTokenValue(str, token, tmp))
258                 return false;
259         num = convert<int>(tmp);
260         return true;
261 }
262
263
264 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
265 {
266         string tmp;
267         return getTokenValue(str, token, tmp) && string2type(tmp, num);
268 }
269
270
271 bool getTokenValue(string const & str, char const * token,
272                                    LyXTabular::VAlignment & num)
273 {
274         string tmp;
275         return getTokenValue(str, token, tmp) && string2type(tmp, num);
276 }
277
278
279 bool getTokenValue(string const & str, char const * token,
280                                    LyXTabular::BoxType & num)
281 {
282         string tmp;
283         return getTokenValue(str, token, tmp) && string2type(tmp, num);
284 }
285
286
287 bool getTokenValue(string const & str, char const * token, bool & flag)
288 {
289         // set the flag always to false as this should be the default for bools
290         // not in the file-format.
291         flag = false;
292         string tmp;
293         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
294 }
295
296
297 bool getTokenValue(string const & str, char const * token, LyXLength & len)
298 {
299         // set the lenght to be zero() as default as this it should be if not
300         // in the file format.
301         len = LyXLength();
302         string tmp;
303         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
304 }
305
306
307 bool getTokenValue(string const & str, char const * token, LyXLength & len, bool & flag)
308 {
309         len = LyXLength();
310         flag = false;
311         string tmp;
312         if (!getTokenValue(str, token, tmp))
313                 return false;
314         if (tmp == "default") {
315                 flag = true;
316                 return  true;
317         }
318         return isValidLength(tmp, &len);
319 }
320
321
322 void l_getline(istream & is, string & str)
323 {
324         str.erase();
325         while (str.empty()) {
326                 getline(is, str);
327                 if (!str.empty() && str[str.length() - 1] == '\r')
328                         str.erase(str.length() - 1);
329         }
330 }
331
332 } // namespace
333
334 /// Define a few methods for the inner structs
335
336 LyXTabular::cellstruct::cellstruct(BufferParams const & bp)
337         : cellno(0),
338           width_of_cell(0),
339           multicolumn(LyXTabular::CELL_NORMAL),
340           alignment(LYX_ALIGN_CENTER),
341           valignment(LYX_VALIGN_TOP),
342           top_line(true),
343           bottom_line(false),
344           left_line(true),
345           right_line(false),
346           usebox(BOX_NONE),
347           rotate(false),
348           inset(new InsetText(bp))
349 {}
350
351
352 LyXTabular::cellstruct::cellstruct(cellstruct const & cs)
353         : cellno(cs.cellno),
354           width_of_cell(cs.width_of_cell),
355           multicolumn(cs.multicolumn),
356           alignment(cs.alignment),
357           valignment(cs.valignment),
358           top_line(cs.top_line),
359           bottom_line(cs.bottom_line),
360           left_line(cs.left_line),
361           right_line(cs.right_line),
362           usebox(cs.usebox),
363           rotate(cs.rotate),
364           align_special(cs.align_special),
365           p_width(cs.p_width),
366           inset(dynamic_cast<InsetText*>(cs.inset->clone().release()))
367 {}
368
369
370 LyXTabular::cellstruct &
371 LyXTabular::cellstruct::operator=(cellstruct cs)
372 {
373         swap(cs);
374         return *this;
375 }
376
377
378 void
379 LyXTabular::cellstruct::swap(cellstruct & rhs)
380 {
381         std::swap(cellno, rhs.cellno);
382         std::swap(width_of_cell, rhs.width_of_cell);
383         std::swap(multicolumn, rhs.multicolumn);
384         std::swap(alignment, rhs.alignment);
385         std::swap(valignment, rhs.valignment);
386         std::swap(top_line, rhs.top_line);
387         std::swap(bottom_line, rhs.bottom_line);
388         std::swap(left_line, rhs.left_line);
389         std::swap(right_line, rhs.right_line);
390         std::swap(usebox, rhs.usebox);
391         std::swap(rotate, rhs.rotate);
392         std::swap(align_special, rhs.align_special);
393         p_width.swap(rhs.p_width);
394         inset.swap(rhs.inset);
395 }
396
397
398 LyXTabular::rowstruct::rowstruct()
399         : ascent_of_row(0),
400           descent_of_row(0),
401           top_line(true),
402           bottom_line(false),
403           top_space_default(false),
404           bottom_space_default(false),
405           interline_space_default(false),
406           endhead(false),
407           endfirsthead(false),
408           endfoot(false),
409           endlastfoot(false),
410           newpage(false)
411 {}
412
413
414 LyXTabular::columnstruct::columnstruct()
415         : alignment(LYX_ALIGN_CENTER),
416           valignment(LYX_VALIGN_TOP),
417           left_line(true),
418           right_line(false),
419           width_of_column(0)
420 {
421 }
422
423
424 LyXTabular::ltType::ltType()
425         : topDL(false),
426           bottomDL(false),
427           empty(false)
428 {}
429
430
431 LyXTabular::LyXTabular(BufferParams const & bp, row_type rows_arg,
432                        col_type columns_arg)
433 {
434         init(bp, rows_arg, columns_arg);
435 }
436
437
438 // activates all lines and sets all widths to 0
439 void LyXTabular::init(BufferParams const & bp, row_type rows_arg,
440                       col_type columns_arg)
441 {
442         rows_    = rows_arg;
443         columns_ = columns_arg;
444         row_info = row_vector(rows_);
445         column_info = column_vector(columns_);
446         cell_info = cell_vvector(rows_, cell_vector(columns_, cellstruct(bp)));
447         row_info.reserve(10);
448         column_info.reserve(10);
449         cell_info.reserve(100);
450         fixCellNums();
451         for (row_type i = 0; i < rows_; ++i)
452                 cell_info[i].back().right_line = true;
453         row_info.back().bottom_line = true;
454         row_info.front().bottom_line = true;
455         column_info.back().right_line = true;
456         is_long_tabular = false;
457         rotate = false;
458         use_booktabs = false;
459 }
460
461
462 void LyXTabular::fixCellNums()
463 {
464         idx_type cellno = 0;
465         for (row_type i = 0; i < rows_; ++i) {
466                 for (col_type j = 0; j < columns_; ++j) {
467                         // When debugging it can be nice to set
468                         // this to true.
469                         cell_info[i][j].inset->setDrawFrame(false);
470                         cell_info[i][j].cellno = cellno++;
471                 }
472                 cell_info[i].back().right_line = true;
473         }
474
475         set_row_column_number_info();
476 }
477
478
479 void LyXTabular::appendRow(BufferParams const & bp, idx_type const cell)
480 {
481         ++rows_;
482
483         row_type const row = row_of_cell(cell);
484
485         row_vector::iterator rit = row_info.begin() + row;
486         row_info.insert(rit, rowstruct());
487         // now set the values of the row before
488         row_info[row] = row_info[row + 1];
489
490         cell_vvector old(rows_ - 1);
491         for (row_type i = 0; i < rows_ - 1; ++i)
492                 swap(cell_info[i], old[i]);
493
494         cell_info = cell_vvector(rows_, cell_vector(columns_, cellstruct(bp)));
495
496         for (row_type i = 0; i <= row; ++i)
497                 swap(cell_info[i], old[i]);
498         for (row_type i = row + 2; i < rows_; ++i)
499                 swap(cell_info[i], old[i - 1]);
500
501         if (bp.trackChanges)
502                 // FIXME: Change Tracking (MG)
503                 for (col_type j = 0; j < columns_; ++j)
504                         cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
505
506         set_row_column_number_info();
507 }
508
509
510 void LyXTabular::deleteRow(row_type const row)
511 {
512         // Not allowed to delete last row
513         if (rows_ == 1)
514                 return;
515
516         row_info.erase(row_info.begin() + row);
517         cell_info.erase(cell_info.begin() + row);
518         --rows_;
519         fixCellNums();
520 }
521
522
523 void LyXTabular::copyRow(BufferParams const & bp, row_type const row)
524 {
525         ++rows_;
526
527         row_info.insert(row_info.begin() + row, row_info[row]);
528         cell_info.insert(cell_info.begin() + row, cell_info[row]);
529
530         if (bp.trackChanges)
531                 // FIXME: Change Tracking (MG)
532                 for (col_type j = 0; j < columns_; ++j)
533                         cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
534
535         set_row_column_number_info();
536 }
537
538
539 void LyXTabular::appendColumn(BufferParams const & bp, idx_type const cell)
540 {
541         ++columns_;
542
543         col_type const column = column_of_cell(cell);
544         column_vector::iterator cit = column_info.begin() + column + 1;
545         column_info.insert(cit, columnstruct());
546         // set the column values of the column before
547         column_info[column + 1] = column_info[column];
548
549         for (row_type i = 0; i < rows_; ++i) {
550                 cell_info[i].insert(cell_info[i].begin() + column + 1, cellstruct(bp));
551
552                 // care about multicolumns
553                 if (cell_info[i][column + 1].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
554                         cell_info[i][column + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
555
556                 if (column + 2 >= columns_
557                     || cell_info[i][column + 2].multicolumn != CELL_PART_OF_MULTICOLUMN)
558                         cell_info[i][column + 1].multicolumn = LyXTabular::CELL_NORMAL;
559         }
560         //++column;
561         for (row_type i = 0; i < rows_; ++i) {
562                 cell_info[i][column + 1].inset->clear();
563                 // FIXME: Change Tracking (MG)
564                 if (bp.trackChanges)
565                         cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
566         }
567         fixCellNums();
568 }
569
570
571 void LyXTabular::deleteColumn(col_type const column)
572 {
573         // Not allowed to delete last column
574         if (columns_ == 1)
575                 return;
576
577         column_info.erase(column_info.begin() + column);
578         for (row_type i = 0; i < rows_; ++i)
579                 cell_info[i].erase(cell_info[i].begin() + column);
580         --columns_;
581         fixCellNums();
582 }
583
584
585 void LyXTabular::copyColumn(BufferParams const & bp, col_type const column)
586 {
587         ++columns_;
588
589         column_info.insert(column_info.begin() + column, column_info[column]);
590
591         for (row_type i = 0; i < rows_; ++i)
592                 cell_info[i].insert(cell_info[i].begin() + column, cell_info[i][column]);
593
594         if (bp.trackChanges)
595                 // FIXME: Change Tracking (MG)
596                 for (row_type i = 0; i < rows_; ++i)
597                         cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
598         fixCellNums();
599 }
600
601
602 void LyXTabular::set_row_column_number_info()
603 {
604         numberofcells = 0;
605         for (row_type row = 0; row < rows_; ++row) {
606                 for (col_type column = 0; column < columns_; ++column) {
607                         if (cell_info[row][column].multicolumn
608                                 != LyXTabular::CELL_PART_OF_MULTICOLUMN)
609                                 ++numberofcells;
610                         if (numberofcells == 0)
611                                 // FIXME: Is this intended?
612                                 cell_info[row][column].cellno = npos;
613                         else
614                                 cell_info[row][column].cellno =
615                                         numberofcells - 1;
616                 }
617         }
618
619         rowofcell.resize(numberofcells);
620         columnofcell.resize(numberofcells);
621
622         row_type row = 0;
623         col_type column = 0;
624         for (idx_type c = 0;
625                  c < numberofcells && row < rows_ && column < columns_;) {
626                 rowofcell[c] = row;
627                 columnofcell[c] = column;
628                 ++c;
629                 do {
630                         ++column;
631                 } while (column < columns_ &&
632                                  cell_info[row][column].multicolumn
633                                  == LyXTabular::CELL_PART_OF_MULTICOLUMN);
634
635                 if (column == columns_) {
636                         column = 0;
637                         ++row;
638                 }
639         }
640
641         for (row_type row = 0; row < rows_; ++row) {
642                 for (col_type column = 0; column < columns_; ++column) {
643                         if (isPartOfMultiColumn(row,column))
644                                 continue;
645                         cell_info[row][column].inset->setAutoBreakRows(
646                                 !getPWidth(getCellNumber(row, column)).zero());
647                 }
648         }
649 }
650
651
652 LyXTabular::idx_type LyXTabular::getNumberOfCells() const
653 {
654         return numberofcells;
655 }
656
657
658 LyXTabular::idx_type LyXTabular::numberOfCellsInRow(idx_type const cell) const
659 {
660         row_type const row = row_of_cell(cell);
661         idx_type result = 0;
662         for (col_type i = 0; i < columns_; ++i)
663                 if (cell_info[row][i].multicolumn != LyXTabular::CELL_PART_OF_MULTICOLUMN)
664                         ++result;
665         return result;
666 }
667
668
669 bool LyXTabular::topLine(idx_type const cell, bool const onlycolumn) const
670 {
671         if (!onlycolumn && isMultiColumn(cell) &&
672             !(use_booktabs && row_of_cell(cell) == 0))
673                 return cellinfo_of_cell(cell).top_line;
674         return row_info[row_of_cell(cell)].top_line;
675 }
676
677
678 bool LyXTabular::bottomLine(idx_type const cell, bool onlycolumn) const
679 {
680         if (!onlycolumn && isMultiColumn(cell) &&
681             !(use_booktabs && isLastRow(cell)))
682                 return cellinfo_of_cell(cell).bottom_line;
683         return row_info[row_of_cell(cell)].bottom_line;
684 }
685
686
687 bool LyXTabular::leftLine(idx_type cell, bool onlycolumn) const
688 {
689         if (use_booktabs)
690                 return false;
691         if (!onlycolumn && isMultiColumn(cell) &&
692                 (isFirstCellInRow(cell) || isMultiColumn(cell-1)))
693         {
694                 if (cellinfo_of_cell(cell).align_special.empty())
695                         return cellinfo_of_cell(cell).left_line;
696                 return prefixIs(ltrim(cellinfo_of_cell(cell).align_special), "|");
697         }
698         if (column_info[column_of_cell(cell)].align_special.empty())
699                 return column_info[column_of_cell(cell)].left_line;
700         return prefixIs(ltrim(column_info[column_of_cell(cell)].align_special), "|");
701 }
702
703
704 bool LyXTabular::rightLine(idx_type cell, bool onlycolumn) const
705 {
706         if (use_booktabs)
707                 return false;
708         if (!onlycolumn && isMultiColumn(cell) &&
709                 (isLastCellInRow(cell) || isMultiColumn(cell + 1)))
710         {
711                 if (cellinfo_of_cell(cell).align_special.empty())
712                         return cellinfo_of_cell(cell).right_line;
713                 return suffixIs(rtrim(cellinfo_of_cell(cell).align_special), "|");
714         }
715         if (column_info[column_of_cell(cell)].align_special.empty())
716                 return column_info[right_column_of_cell(cell)].right_line;
717         return suffixIs(rtrim(column_info[column_of_cell(cell)].align_special), "|");
718 }
719
720
721 bool LyXTabular::topAlreadyDrawn(idx_type cell) const
722 {
723         row_type row = row_of_cell(cell);
724         if (row > 0 && !getAdditionalHeight(row)) {
725                 col_type column = column_of_cell(cell);
726                 --row;
727                 while (column
728                            && cell_info[row][column].multicolumn
729                            == LyXTabular::CELL_PART_OF_MULTICOLUMN)
730                         --column;
731                 if (cell_info[row][column].multicolumn == LyXTabular::CELL_NORMAL)
732                         return row_info[row].bottom_line;
733                 else
734                         return cell_info[row][column].bottom_line;
735         }
736         return false;
737 }
738
739
740 bool LyXTabular::leftAlreadyDrawn(idx_type cell) const
741 {
742         col_type column = column_of_cell(cell);
743         if (column > 0) {
744                 row_type row = row_of_cell(cell);
745                 while (--column &&
746                            (cell_info[row][column].multicolumn ==
747                                 LyXTabular::CELL_PART_OF_MULTICOLUMN));
748                 if (getAdditionalWidth(cell_info[row][column].cellno))
749                         return false;
750                 return rightLine(cell_info[row][column].cellno);
751         }
752         return false;
753 }
754
755
756 bool LyXTabular::isLastRow(idx_type cell) const
757 {
758         return row_of_cell(cell) == rows_ - 1;
759 }
760
761
762 int LyXTabular::getAdditionalHeight(row_type row) const
763 {
764         if (!row || row >= rows_)
765                 return 0;
766
767         bool top = true;
768         bool bottom = true;
769
770         for (col_type column = 0; column < columns_ && bottom; ++column) {
771                 switch (cell_info[row - 1][column].multicolumn) {
772                 case LyXTabular::CELL_BEGIN_OF_MULTICOLUMN:
773                         bottom = cell_info[row - 1][column].bottom_line;
774                         break;
775                 case LyXTabular::CELL_NORMAL:
776                         bottom = row_info[row - 1].bottom_line;
777                 }
778         }
779         for (col_type column = 0; column < columns_ && top; ++column) {
780                 switch (cell_info[row][column].multicolumn) {
781                 case LyXTabular::CELL_BEGIN_OF_MULTICOLUMN:
782                         top = cell_info[row][column].top_line;
783                         break;
784                 case LyXTabular::CELL_NORMAL:
785                         top = row_info[row].top_line;
786                 }
787         }
788         int const interline_space = row_info[row - 1].interline_space_default ?
789                 default_line_space :
790                 row_info[row - 1].interline_space.inPixels(width_of_tabular);
791         if (top && bottom)
792                 return interline_space + WIDTH_OF_LINE;
793         return interline_space;
794 }
795
796
797 int LyXTabular::getAdditionalWidth(idx_type cell) const
798 {
799         // internally already set in setWidthOfCell
800         // used to get it back in text.C
801         col_type const col = right_column_of_cell(cell);
802         row_type const row = row_of_cell(cell);
803         if (col < columns_ - 1 && rightLine(cell) &&
804                 leftLine(cell_info[row][col+1].cellno)) // column_info[col+1].left_line)
805         {
806                 return WIDTH_OF_LINE;
807         }
808         return 0;
809 }
810
811
812 // returns the maximum over all rows
813 int LyXTabular::getWidthOfColumn(idx_type cell) const
814 {
815         col_type const column1 = column_of_cell(cell);
816         col_type const column2 = right_column_of_cell(cell);
817         int result = 0;
818         for (col_type i = column1; i <= column2; ++i)
819                 result += column_info[i].width_of_column;
820         return result;
821 }
822
823
824 int LyXTabular::getWidthOfTabular() const
825 {
826         return width_of_tabular;
827 }
828
829
830 // returns true if a complete update is necessary, otherwise false
831 bool LyXTabular::setWidthOfMulticolCell(idx_type cell, int new_width)
832 {
833         if (!isMultiColumn(cell))
834                 return false;
835
836         row_type const row = row_of_cell(cell);
837         col_type const column1 = column_of_cell(cell);
838         col_type const column2 = right_column_of_cell(cell);
839         int const old_val = cell_info[row][column2].width_of_cell;
840
841         // first set columns to 0 so we can calculate the right width
842         for (col_type i = column1; i <= column2; ++i) {
843                 cell_info[row][i].width_of_cell = 0;
844         }
845         // set the width to MAX_WIDTH until width > 0
846         int width = new_width + 2 * WIDTH_OF_LINE;
847         col_type i = column1;
848         for (; i < column2 && width > column_info[i].width_of_column; ++i) {
849                 cell_info[row][i].width_of_cell = column_info[i].width_of_column;
850                 width -= column_info[i].width_of_column;
851         }
852         if (width > 0) {
853                 cell_info[row][i].width_of_cell = width;
854         }
855         if (old_val != cell_info[row][column2].width_of_cell) {
856                 // in this case we have to recalculate all multicolumn cells which
857                 // have this column as one of theirs but not as last one
858                 calculate_width_of_column_NMC(i);
859                 recalculateMulticolumnsOfColumn(i);
860                 calculate_width_of_column(i);
861         }
862         return true;
863 }
864
865
866 void LyXTabular::recalculateMulticolumnsOfColumn(col_type column)
867 {
868         // the last column does not have to be recalculated because all
869         // multicolumns will have here there last multicolumn cell which
870         // always will have the whole rest of the width of the cell.
871         if (columns_ < 2 || column > (columns_ - 2))
872                 return;
873         for (row_type row = 0; row < rows_; ++row) {
874                 int mc = cell_info[row][column].multicolumn;
875                 int nmc = cell_info[row][column+1].multicolumn;
876                 // we only have to update multicolumns which do not have this
877                 // column as their last column!
878                 if (mc == CELL_BEGIN_OF_MULTICOLUMN ||
879                           (mc == CELL_PART_OF_MULTICOLUMN &&
880                            nmc == CELL_PART_OF_MULTICOLUMN))
881                 {
882                         idx_type const cellno = cell_info[row][column].cellno;
883                         setWidthOfMulticolCell(cellno,
884                                                getWidthOfCell(cellno) - 2 * WIDTH_OF_LINE);
885                 }
886         }
887 }
888
889
890 void LyXTabular::setWidthOfCell(idx_type cell, int new_width)
891 {
892         row_type const row = row_of_cell(cell);
893         col_type const column1 = column_of_cell(cell);
894         bool tmp = false;
895         int width = 0;
896         int add_width = 0;
897
898         if (rightLine(cell_info[row][column1].cellno, true) &&
899                 column1 < columns_ - 1 &&
900                 leftLine(cell_info[row][column1+1].cellno, true))
901         {
902                 add_width = WIDTH_OF_LINE;
903         }
904
905         if (getWidthOfCell(cell) == new_width + 2 * WIDTH_OF_LINE + add_width)
906                 return;
907
908         if (isMultiColumnReal(cell)) {
909                 tmp = setWidthOfMulticolCell(cell, new_width);
910         } else {
911                 width = new_width + 2 * WIDTH_OF_LINE + add_width;
912                 cell_info[row][column1].width_of_cell = width;
913                 tmp = calculate_width_of_column_NMC(column1);
914                 if (tmp)
915                         recalculateMulticolumnsOfColumn(column1);
916         }
917         if (tmp) {
918                 for (col_type i = 0; i < columns_; ++i)
919                         calculate_width_of_column(i);
920                 calculate_width_of_tabular();
921         }
922 }
923
924
925 void LyXTabular::setAlignment(idx_type cell, LyXAlignment align,
926                               bool onlycolumn)
927 {
928         if (!isMultiColumn(cell) || onlycolumn)
929                 column_info[column_of_cell(cell)].alignment = align;
930         if (!onlycolumn)
931                 cellinfo_of_cell(cell).alignment = align;
932 }
933
934
935 void LyXTabular::setVAlignment(idx_type cell, VAlignment align,
936                                bool onlycolumn)
937 {
938         if (!isMultiColumn(cell) || onlycolumn)
939                 column_info[column_of_cell(cell)].valignment = align;
940         if (!onlycolumn)
941                 cellinfo_of_cell(cell).valignment = align;
942 }
943
944
945 namespace {
946
947 /**
948  * Allow line and paragraph breaks for fixed width cells or disallow them,
949  * merge cell paragraphs and reset layout to standard for variable width
950  * cells.
951  */
952 void toggleFixedWidth(LCursor & cur, InsetText * inset, bool fixedWidth)
953 {
954         inset->setAutoBreakRows(fixedWidth);
955         if (fixedWidth)
956                 return;
957
958         // merge all paragraphs to one
959         BufferParams const & bp =
960                 inset->getText(0)->bv_owner->buffer()->params();
961         while (inset->paragraphs().size() > 1)
962                 mergeParagraph(bp, inset->paragraphs(), 0);
963
964         // reset layout
965         cur.push(*inset);
966         // undo information has already been recorded
967         inset->getText(0)->setLayout(0, cur.lastpit() + 1,
968                         bp.getLyXTextClass().defaultLayoutName());
969         cur.pop();
970 }
971
972 }
973
974
975 void LyXTabular::setColumnPWidth(LCursor & cur, idx_type cell,
976                 LyXLength const & width)
977 {
978         col_type const j = column_of_cell(cell);
979
980         column_info[j].p_width = width;
981         for (row_type i = 0; i < rows_; ++i) {
982                 idx_type const cell = getCellNumber(i, j);
983                 // because of multicolumns
984                 toggleFixedWidth(cur, getCellInset(cell).get(),
985                                  !getPWidth(cell).zero());
986         }
987         // cur paragraph can become invalid after paragraphs were merged
988         if (cur.pit() > cur.lastpit())
989                 cur.pit() = cur.lastpit();
990         // cur position can become invalid after newlines were removed
991         if (cur.pos() > cur.lastpos())
992                 cur.pos() = cur.lastpos();
993 }
994
995
996 bool LyXTabular::setMColumnPWidth(LCursor & cur, idx_type cell,
997                 LyXLength const & width)
998 {
999         if (!isMultiColumn(cell))
1000                 return false;
1001
1002         cellinfo_of_cell(cell).p_width = width;
1003         toggleFixedWidth(cur, getCellInset(cell).get(), !width.zero());
1004         // cur paragraph can become invalid after paragraphs were merged
1005         if (cur.pit() > cur.lastpit())
1006                 cur.pit() = cur.lastpit();
1007         // cur position can become invalid after newlines were removed
1008         if (cur.pos() > cur.lastpos())
1009                 cur.pos() = cur.lastpos();
1010         return true;
1011 }
1012
1013
1014 void LyXTabular::setAlignSpecial(idx_type cell, string const & special,
1015                                  LyXTabular::Feature what)
1016 {
1017         if (what == SET_SPECIAL_MULTI)
1018                 cellinfo_of_cell(cell).align_special = special;
1019         else
1020                 column_info[column_of_cell(cell)].align_special = special;
1021 }
1022
1023
1024 void LyXTabular::setAllLines(idx_type cell, bool line)
1025 {
1026         setTopLine(cell, line);
1027         setBottomLine(cell, line);
1028         setRightLine(cell, line);
1029         setLeftLine(cell, line);
1030 }
1031
1032
1033 void LyXTabular::setTopLine(idx_type cell, bool line, bool onlycolumn)
1034 {
1035         row_type const row = row_of_cell(cell);
1036         if (onlycolumn || !isMultiColumn(cell))
1037                 row_info[row].top_line = line;
1038         else
1039                 cellinfo_of_cell(cell).top_line = line;
1040 }
1041
1042
1043 void LyXTabular::setBottomLine(idx_type cell, bool line, bool onlycolumn)
1044 {
1045         if (onlycolumn || !isMultiColumn(cell))
1046                 row_info[row_of_cell(cell)].bottom_line = line;
1047         else
1048                 cellinfo_of_cell(cell).bottom_line = line;
1049 }
1050
1051
1052 void LyXTabular::setLeftLine(idx_type cell, bool line, bool onlycolumn)
1053 {
1054         if (onlycolumn || !isMultiColumn(cell))
1055                 column_info[column_of_cell(cell)].left_line = line;
1056         else
1057                 cellinfo_of_cell(cell).left_line = line;
1058 }
1059
1060
1061 void LyXTabular::setRightLine(idx_type cell, bool line, bool onlycolumn)
1062 {
1063         if (onlycolumn || !isMultiColumn(cell))
1064                 column_info[right_column_of_cell(cell)].right_line = line;
1065         else
1066                 cellinfo_of_cell(cell).right_line = line;
1067 }
1068
1069
1070 LyXAlignment LyXTabular::getAlignment(idx_type cell, bool onlycolumn) const
1071 {
1072         if (!onlycolumn && isMultiColumn(cell))
1073                 return cellinfo_of_cell(cell).alignment;
1074         return column_info[column_of_cell(cell)].alignment;
1075 }
1076
1077
1078 LyXTabular::VAlignment
1079 LyXTabular::getVAlignment(idx_type cell, bool onlycolumn) const
1080 {
1081         if (!onlycolumn && isMultiColumn(cell))
1082                 return cellinfo_of_cell(cell).valignment;
1083         return column_info[column_of_cell(cell)].valignment;
1084 }
1085
1086
1087 LyXLength const LyXTabular::getPWidth(idx_type cell) const
1088 {
1089         if (isMultiColumn(cell))
1090                 return cellinfo_of_cell(cell).p_width;
1091         return column_info[column_of_cell(cell)].p_width;
1092 }
1093
1094
1095 LyXLength const LyXTabular::getColumnPWidth(idx_type cell) const
1096 {
1097         return column_info[column_of_cell(cell)].p_width;
1098 }
1099
1100
1101 LyXLength const LyXTabular::getMColumnPWidth(idx_type cell) const
1102 {
1103         if (isMultiColumn(cell))
1104                 return cellinfo_of_cell(cell).p_width;
1105         return LyXLength();
1106 }
1107
1108
1109 string const LyXTabular::getAlignSpecial(idx_type cell, int what) const
1110 {
1111         if (what == SET_SPECIAL_MULTI)
1112                 return cellinfo_of_cell(cell).align_special;
1113         return column_info[column_of_cell(cell)].align_special;
1114 }
1115
1116
1117 int LyXTabular::getWidthOfCell(idx_type cell) const
1118 {
1119         row_type const row = row_of_cell(cell);
1120         col_type const column1 = column_of_cell(cell);
1121         col_type const column2 = right_column_of_cell(cell);
1122         int result = 0;
1123         for (col_type i = column1; i <= column2; ++i)
1124                 result += cell_info[row][i].width_of_cell;
1125         return result;
1126 }
1127
1128
1129 int LyXTabular::getBeginningOfTextInCell(idx_type cell) const
1130 {
1131         int x = 0;
1132
1133         switch (getAlignment(cell)) {
1134         case LYX_ALIGN_CENTER:
1135                 x += (getWidthOfColumn(cell) - getWidthOfCell(cell)) / 2;
1136                 break;
1137         case LYX_ALIGN_RIGHT:
1138                 x += getWidthOfColumn(cell) - getWidthOfCell(cell);
1139                 // + getAdditionalWidth(cell);
1140                 break;
1141         default:
1142                 // LYX_ALIGN_LEFT: nothing :-)
1143                 break;
1144         }
1145
1146         // the LaTeX Way :-(
1147         x += WIDTH_OF_LINE;
1148         return x;
1149 }
1150
1151
1152 bool LyXTabular::isFirstCellInRow(idx_type cell) const
1153 {
1154         return column_of_cell(cell) == 0;
1155 }
1156
1157
1158 LyXTabular::idx_type LyXTabular::getFirstCellInRow(row_type row) const
1159 {
1160         if (row > rows_ - 1)
1161                 row = rows_ - 1;
1162         return cell_info[row][0].cellno;
1163 }
1164
1165
1166 bool LyXTabular::isLastCellInRow(idx_type cell) const
1167 {
1168         return right_column_of_cell(cell) == columns_ - 1;
1169 }
1170
1171
1172 LyXTabular::idx_type LyXTabular::getLastCellInRow(row_type row) const
1173 {
1174         if (row > rows_ - 1)
1175                 row = rows_ - 1;
1176         return cell_info[row][columns_-1].cellno;
1177 }
1178
1179
1180 void LyXTabular::calculate_width_of_column(col_type column)
1181 {
1182         int maximum = 0;
1183         for (row_type i = 0; i < rows_; ++i)
1184                 maximum = max(cell_info[i][column].width_of_cell, maximum);
1185         column_info[column].width_of_column = maximum;
1186 }
1187
1188
1189 //
1190 // Calculate the columns regarding ONLY the normal cells and if this
1191 // column is inside a multicolumn cell then use it only if its the last
1192 // column of this multicolumn cell as this gives an added width to the
1193 // column, all the rest should be adapted!
1194 //
1195 bool LyXTabular::calculate_width_of_column_NMC(col_type column)
1196 {
1197         int const old_column_width = column_info[column].width_of_column;
1198         int max = 0;
1199         for (row_type i = 0; i < rows_; ++i) {
1200                 idx_type cell = getCellNumber(i, column);
1201                 bool ismulti = isMultiColumnReal(cell);
1202                 if ((!ismulti || column == right_column_of_cell(cell)) &&
1203                         cell_info[i][column].width_of_cell > max)
1204                 {
1205                         max = cell_info[i][column].width_of_cell;
1206                 }
1207         }
1208         column_info[column].width_of_column = max;
1209         return column_info[column].width_of_column != old_column_width;
1210 }
1211
1212
1213 void LyXTabular::calculate_width_of_tabular()
1214 {
1215         width_of_tabular = 0;
1216         for (col_type i = 0; i < columns_; ++i)
1217                 width_of_tabular += column_info[i].width_of_column;
1218 }
1219
1220
1221 LyXTabular::row_type LyXTabular::row_of_cell(idx_type cell) const
1222 {
1223         if (cell >= numberofcells)
1224                 return rows_ - 1;
1225         if (cell == npos)
1226                 return 0;
1227         return rowofcell[cell];
1228 }
1229
1230
1231 LyXTabular::col_type LyXTabular::column_of_cell(idx_type cell) const
1232 {
1233         if (cell >= numberofcells)
1234                 return columns_ - 1;
1235         if (cell == npos)
1236                 return 0;
1237         return columnofcell[cell];
1238 }
1239
1240
1241 LyXTabular::col_type LyXTabular::right_column_of_cell(idx_type cell) const
1242 {
1243         row_type const row = row_of_cell(cell);
1244         col_type column = column_of_cell(cell);
1245         while (column < columns_ - 1 &&
1246                    cell_info[row][column + 1].multicolumn == LyXTabular::CELL_PART_OF_MULTICOLUMN)
1247                 ++column;
1248         return column;
1249 }
1250
1251
1252 void LyXTabular::write(Buffer const & buf, ostream & os) const
1253 {
1254         // header line
1255         os << "<lyxtabular"
1256            << write_attribute("version", 3)
1257            << write_attribute("rows", rows_)
1258            << write_attribute("columns", columns_)
1259            << ">\n";
1260         // global longtable options
1261         os << "<features"
1262            << write_attribute("rotate", rotate)
1263            << write_attribute("booktabs", use_booktabs)
1264            << write_attribute("islongtable", is_long_tabular)
1265            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1266            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1267            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1268            << write_attribute("headTopDL", endhead.topDL)
1269            << write_attribute("headBottomDL", endhead.bottomDL)
1270            << write_attribute("footTopDL", endfoot.topDL)
1271            << write_attribute("footBottomDL", endfoot.bottomDL)
1272            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1273            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1274            << write_attribute("lastFootEmpty", endlastfoot.empty)
1275            << ">\n";
1276         for (col_type j = 0; j < columns_; ++j) {
1277                 os << "<column"
1278                    << write_attribute("alignment", column_info[j].alignment)
1279                    << write_attribute("valignment", column_info[j].valignment)
1280                    << write_attribute("leftline", column_info[j].left_line)
1281                    << write_attribute("rightline", column_info[j].right_line)
1282                    << write_attribute("width", column_info[j].p_width.asString())
1283                    << write_attribute("special", column_info[j].align_special)
1284                    << ">\n";
1285         }
1286         for (row_type i = 0; i < rows_; ++i) {
1287                 os << "<row"
1288                    << write_attribute("topline", row_info[i].top_line)
1289                    << write_attribute("bottomline", row_info[i].bottom_line);
1290                 static const string def("default");
1291                 if (row_info[i].top_space_default)
1292                         os << write_attribute("topspace", def);
1293                 else
1294                         os << write_attribute("topspace", row_info[i].top_space);
1295                 if (row_info[i].bottom_space_default)
1296                         os << write_attribute("bottomspace", def);
1297                 else
1298                         os << write_attribute("bottomspace", row_info[i].bottom_space);
1299                 if (row_info[i].interline_space_default)
1300                         os << write_attribute("interlinespace", def);
1301                 else
1302                         os << write_attribute("interlinespace", row_info[i].interline_space);
1303                 os << write_attribute("endhead", row_info[i].endhead)
1304                    << write_attribute("endfirsthead", row_info[i].endfirsthead)
1305                    << write_attribute("endfoot", row_info[i].endfoot)
1306                    << write_attribute("endlastfoot", row_info[i].endlastfoot)
1307                    << write_attribute("newpage", row_info[i].newpage)
1308                    << ">\n";
1309                 for (col_type j = 0; j < columns_; ++j) {
1310                         os << "<cell"
1311                            << write_attribute("multicolumn", cell_info[i][j].multicolumn)
1312                            << write_attribute("alignment", cell_info[i][j].alignment)
1313                            << write_attribute("valignment", cell_info[i][j].valignment)
1314                            << write_attribute("topline", cell_info[i][j].top_line)
1315                            << write_attribute("bottomline", cell_info[i][j].bottom_line)
1316                            << write_attribute("leftline", cell_info[i][j].left_line)
1317                            << write_attribute("rightline", cell_info[i][j].right_line)
1318                            << write_attribute("rotate", cell_info[i][j].rotate)
1319                            << write_attribute("usebox", cell_info[i][j].usebox)
1320                            << write_attribute("width", cell_info[i][j].p_width)
1321                            << write_attribute("special", cell_info[i][j].align_special)
1322                            << ">\n";
1323                         os << "\\begin_inset ";
1324                         cell_info[i][j].inset->write(buf, os);
1325                         os << "\n\\end_inset\n"
1326                            << "</cell>\n";
1327                 }
1328                 os << "</row>\n";
1329         }
1330         os << "</lyxtabular>\n";
1331 }
1332
1333
1334 void LyXTabular::read(Buffer const & buf, LyXLex & lex)
1335 {
1336         string line;
1337         istream & is = lex.getStream();
1338
1339         l_getline(is, line);
1340         if (!prefixIs(line, "<lyxtabular ")
1341                 && !prefixIs(line, "<LyXTabular ")) {
1342                 BOOST_ASSERT(false);
1343                 return;
1344         }
1345
1346         int version;
1347         if (!getTokenValue(line, "version", version))
1348                 return;
1349         BOOST_ASSERT(version >= 2);
1350
1351         int rows_arg;
1352         if (!getTokenValue(line, "rows", rows_arg))
1353                 return;
1354         int columns_arg;
1355         if (!getTokenValue(line, "columns", columns_arg))
1356                 return;
1357         init(buf.params(), rows_arg, columns_arg);
1358         l_getline(is, line);
1359         if (!prefixIs(line, "<features")) {
1360                 lyxerr << "Wrong tabular format (expected <features ...> got"
1361                        << line << ')' << endl;
1362                 return;
1363         }
1364         getTokenValue(line, "rotate", rotate);
1365         getTokenValue(line, "booktabs", use_booktabs);
1366         getTokenValue(line, "islongtable", is_long_tabular);
1367         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1368         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1369         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1370         getTokenValue(line, "headTopDL", endhead.topDL);
1371         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1372         getTokenValue(line, "footTopDL", endfoot.topDL);
1373         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1374         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1375         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1376         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1377
1378         for (col_type j = 0; j < columns_; ++j) {
1379                 l_getline(is,line);
1380                 if (!prefixIs(line,"<column")) {
1381                         lyxerr << "Wrong tabular format (expected <column ...> got"
1382                                << line << ')' << endl;
1383                         return;
1384                 }
1385                 getTokenValue(line, "alignment", column_info[j].alignment);
1386                 getTokenValue(line, "valignment", column_info[j].valignment);
1387                 getTokenValue(line, "leftline", column_info[j].left_line);
1388                 getTokenValue(line, "rightline", column_info[j].right_line);
1389                 getTokenValue(line, "width", column_info[j].p_width);
1390                 getTokenValue(line, "special", column_info[j].align_special);
1391         }
1392
1393         for (row_type i = 0; i < rows_; ++i) {
1394                 l_getline(is, line);
1395                 if (!prefixIs(line, "<row")) {
1396                         lyxerr << "Wrong tabular format (expected <row ...> got"
1397                                << line << ')' << endl;
1398                         return;
1399                 }
1400                 getTokenValue(line, "topline", row_info[i].top_line);
1401                 getTokenValue(line, "bottomline", row_info[i].bottom_line);
1402                 getTokenValue(line, "topspace", row_info[i].top_space,
1403                               row_info[i].top_space_default);
1404                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1405                               row_info[i].bottom_space_default);
1406                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1407                               row_info[i].interline_space_default);
1408                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1409                 getTokenValue(line, "endhead", row_info[i].endhead);
1410                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1411                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1412                 getTokenValue(line, "newpage", row_info[i].newpage);
1413                 for (col_type j = 0; j < columns_; ++j) {
1414                         l_getline(is, line);
1415                         if (!prefixIs(line, "<cell")) {
1416                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1417                                        << line << ')' << endl;
1418                                 return;
1419                         }
1420                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1421                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1422                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1423                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1424                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1425                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1426                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1427                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1428                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1429                         getTokenValue(line, "width", cell_info[i][j].p_width);
1430                         getTokenValue(line, "special", cell_info[i][j].align_special);
1431                         l_getline(is, line);
1432                         if (prefixIs(line, "\\begin_inset")) {
1433                                 cell_info[i][j].inset->read(buf, lex);
1434                                 l_getline(is, line);
1435                         }
1436                         if (!prefixIs(line, "</cell>")) {
1437                                 lyxerr << "Wrong tabular format (expected </cell> got"
1438                                        << line << ')' << endl;
1439                                 return;
1440                         }
1441                 }
1442                 l_getline(is, line);
1443                 if (!prefixIs(line, "</row>")) {
1444                         lyxerr << "Wrong tabular format (expected </row> got"
1445                                << line << ')' << endl;
1446                         return;
1447                 }
1448         }
1449         while (!prefixIs(line, "</lyxtabular>")) {
1450                 l_getline(is, line);
1451         }
1452         set_row_column_number_info();
1453 }
1454
1455
1456 bool LyXTabular::isMultiColumn(idx_type cell) const
1457 {
1458         return cellinfo_of_cell(cell).multicolumn != LyXTabular::CELL_NORMAL;
1459 }
1460
1461
1462 bool LyXTabular::isMultiColumnReal(idx_type cell) const
1463 {
1464         return column_of_cell(cell) != right_column_of_cell(cell) &&
1465                         cellinfo_of_cell(cell).multicolumn != LyXTabular::CELL_NORMAL;
1466 }
1467
1468
1469 LyXTabular::cellstruct & LyXTabular::cellinfo_of_cell(idx_type cell) const
1470 {
1471         return cell_info[row_of_cell(cell)][column_of_cell(cell)];
1472 }
1473
1474
1475 void LyXTabular::setMultiColumn(Buffer * buffer, idx_type cell,
1476                                 idx_type number)
1477 {
1478         cellstruct & cs = cellinfo_of_cell(cell);
1479         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1480         cs.alignment = column_info[column_of_cell(cell)].alignment;
1481         cs.top_line = row_info[row_of_cell(cell)].top_line;
1482         cs.bottom_line = row_info[row_of_cell(cell)].bottom_line;
1483         cs.left_line = column_info[column_of_cell(cell)].left_line;
1484         cs.right_line = column_info[column_of_cell(cell+number-1)].right_line;
1485         for (idx_type i = 1; i < number; ++i) {
1486                 cellstruct & cs1 = cellinfo_of_cell(cell + i);
1487                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1488                 cs.inset->appendParagraphs(buffer, cs1.inset->paragraphs());
1489                 cs1.inset->clear();
1490         }
1491         set_row_column_number_info();
1492 }
1493
1494
1495 LyXTabular::idx_type LyXTabular::cells_in_multicolumn(idx_type cell) const
1496 {
1497         row_type const row = row_of_cell(cell);
1498         col_type column = column_of_cell(cell);
1499         idx_type result = 1;
1500         ++column;
1501         while (column < columns_ &&
1502                    cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
1503         {
1504                 ++result;
1505                 ++column;
1506         }
1507         return result;
1508 }
1509
1510
1511 LyXTabular::idx_type LyXTabular::unsetMultiColumn(idx_type cell)
1512 {
1513         row_type const row = row_of_cell(cell);
1514         col_type column = column_of_cell(cell);
1515
1516         idx_type result = 0;
1517
1518         if (cell_info[row][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN) {
1519                 cell_info[row][column].multicolumn = CELL_NORMAL;
1520                 ++column;
1521                 while (column < columns_ &&
1522                            cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
1523                 {
1524                         cell_info[row][column].multicolumn = CELL_NORMAL;
1525                         ++column;
1526                         ++result;
1527                 }
1528         }
1529         set_row_column_number_info();
1530         return result;
1531 }
1532
1533
1534 void LyXTabular::setBookTabs(bool what)
1535 {
1536         use_booktabs = what;
1537 }
1538
1539
1540 bool LyXTabular::useBookTabs() const
1541 {
1542         return use_booktabs;
1543 }
1544
1545
1546 void LyXTabular::setLongTabular(bool what)
1547 {
1548         is_long_tabular = what;
1549 }
1550
1551
1552 bool LyXTabular::isLongTabular() const
1553 {
1554         return is_long_tabular;
1555 }
1556
1557
1558 void LyXTabular::setRotateTabular(bool flag)
1559 {
1560         rotate = flag;
1561 }
1562
1563
1564 bool LyXTabular::getRotateTabular() const
1565 {
1566         return rotate;
1567 }
1568
1569
1570 void LyXTabular::setRotateCell(idx_type cell, bool flag)
1571 {
1572         cellinfo_of_cell(cell).rotate = flag;
1573 }
1574
1575
1576 bool LyXTabular::getRotateCell(idx_type cell) const
1577 {
1578         return cellinfo_of_cell(cell).rotate;
1579 }
1580
1581
1582 bool LyXTabular::needRotating() const
1583 {
1584         if (rotate)
1585                 return true;
1586         for (row_type i = 0; i < rows_; ++i)
1587                 for (col_type j = 0; j < columns_; ++j)
1588                         if (cell_info[i][j].rotate)
1589                                 return true;
1590         return false;
1591 }
1592
1593
1594 bool LyXTabular::isLastCell(idx_type cell) const
1595 {
1596         if (cell + 1 < numberofcells)
1597                 return false;
1598         return true;
1599 }
1600
1601
1602 LyXTabular::idx_type LyXTabular::getCellAbove(idx_type cell) const
1603 {
1604         if (row_of_cell(cell) > 0)
1605                 return cell_info[row_of_cell(cell)-1][column_of_cell(cell)].cellno;
1606         return cell;
1607 }
1608
1609
1610 LyXTabular::idx_type LyXTabular::getCellBelow(idx_type cell) const
1611 {
1612         if (row_of_cell(cell) + 1 < rows_)
1613                 return cell_info[row_of_cell(cell)+1][column_of_cell(cell)].cellno;
1614         return cell;
1615 }
1616
1617
1618 LyXTabular::idx_type LyXTabular::getLastCellAbove(idx_type cell) const
1619 {
1620         if (row_of_cell(cell) == 0)
1621                 return cell;
1622         if (!isMultiColumn(cell))
1623                 return getCellAbove(cell);
1624         return cell_info[row_of_cell(cell) - 1][right_column_of_cell(cell)].cellno;
1625 }
1626
1627
1628 LyXTabular::idx_type LyXTabular::getLastCellBelow(idx_type cell) const
1629 {
1630         if (row_of_cell(cell) + 1 >= rows_)
1631                 return cell;
1632         if (!isMultiColumn(cell))
1633                 return getCellBelow(cell);
1634         return cell_info[row_of_cell(cell) + 1][right_column_of_cell(cell)].cellno;
1635 }
1636
1637
1638 LyXTabular::idx_type LyXTabular::getCellNumber(row_type row,
1639                                                col_type column) const
1640 {
1641         BOOST_ASSERT(column != npos && column < columns_ &&
1642                      row    != npos && row    < rows_);
1643         return cell_info[row][column].cellno;
1644 }
1645
1646
1647 void LyXTabular::setUsebox(idx_type cell, BoxType type)
1648 {
1649         cellinfo_of_cell(cell).usebox = type;
1650 }
1651
1652
1653 LyXTabular::BoxType LyXTabular::getUsebox(idx_type cell) const
1654 {
1655         if (column_info[column_of_cell(cell)].p_width.zero() &&
1656                 !(isMultiColumn(cell) && !cellinfo_of_cell(cell).p_width.zero()))
1657                 return BOX_NONE;
1658         if (cellinfo_of_cell(cell).usebox > 1)
1659                 return cellinfo_of_cell(cell).usebox;
1660         return useParbox(cell);
1661 }
1662
1663
1664 ///
1665 //  This are functions used for the longtable support
1666 ///
1667 void LyXTabular::setLTHead(row_type row, bool flag, ltType const & hd,
1668                            bool first)
1669 {
1670         if (first) {
1671                 endfirsthead = hd;
1672                 if (hd.set)
1673                         row_info[row].endfirsthead = flag;
1674         } else {
1675                 endhead = hd;
1676                 if (hd.set)
1677                         row_info[row].endhead = flag;
1678         }
1679 }
1680
1681
1682 bool LyXTabular::getRowOfLTHead(row_type row, ltType & hd) const
1683 {
1684         hd = endhead;
1685         hd.set = haveLTHead();
1686         return row_info[row].endhead;
1687 }
1688
1689
1690 bool LyXTabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1691 {
1692         hd = endfirsthead;
1693         hd.set = haveLTFirstHead();
1694         return row_info[row].endfirsthead;
1695 }
1696
1697
1698 void LyXTabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1699                            bool last)
1700 {
1701         if (last) {
1702                 endlastfoot = fd;
1703                 if (fd.set)
1704                         row_info[row].endlastfoot = flag;
1705         } else {
1706                 endfoot = fd;
1707                 if (fd.set)
1708                         row_info[row].endfoot = flag;
1709         }
1710 }
1711
1712
1713 bool LyXTabular::getRowOfLTFoot(row_type row, ltType & fd) const
1714 {
1715         fd = endfoot;
1716         fd.set = haveLTFoot();
1717         return row_info[row].endfoot;
1718 }
1719
1720
1721 bool LyXTabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1722 {
1723         fd = endlastfoot;
1724         fd.set = haveLTLastFoot();
1725         return row_info[row].endlastfoot;
1726 }
1727
1728
1729 void LyXTabular::setLTNewPage(row_type row, bool what)
1730 {
1731         row_info[row].newpage = what;
1732 }
1733
1734
1735 bool LyXTabular::getLTNewPage(row_type row) const
1736 {
1737         return row_info[row].newpage;
1738 }
1739
1740
1741 bool LyXTabular::haveLTHead() const
1742 {
1743         for (row_type i = 0; i < rows_; ++i)
1744                 if (row_info[i].endhead)
1745                         return true;
1746         return false;
1747 }
1748
1749
1750 bool LyXTabular::haveLTFirstHead() const
1751 {
1752         if (endfirsthead.empty)
1753                 return false;
1754         for (row_type i = 0; i < rows_; ++i)
1755                 if (row_info[i].endfirsthead)
1756                         return true;
1757         return false;
1758 }
1759
1760
1761 bool LyXTabular::haveLTFoot() const
1762 {
1763         for (row_type i = 0; i < rows_; ++i)
1764                 if (row_info[i].endfoot)
1765                         return true;
1766         return false;
1767 }
1768
1769
1770 bool LyXTabular::haveLTLastFoot() const
1771 {
1772         if (endlastfoot.empty)
1773                 return false;
1774         for (row_type i = 0; i < rows_; ++i)
1775                 if (row_info[i].endlastfoot)
1776                         return true;
1777         return false;
1778 }
1779
1780
1781 // end longtable support functions
1782
1783 void LyXTabular::setAscentOfRow(row_type row, int height)
1784 {
1785         if (row >= rows_ || row_info[row].ascent_of_row == height)
1786                 return;
1787         row_info[row].ascent_of_row = height;
1788 }
1789
1790
1791 void LyXTabular::setDescentOfRow(row_type row, int height)
1792 {
1793         if (row >= rows_ || row_info[row].descent_of_row == height)
1794                 return;
1795         row_info[row].descent_of_row = height;
1796 }
1797
1798
1799 int LyXTabular::getAscentOfRow(row_type row) const
1800 {
1801         if (row >= rows_)
1802                 return 0;
1803         return row_info[row].ascent_of_row;
1804 }
1805
1806
1807 int LyXTabular::getDescentOfRow(row_type row) const
1808 {
1809         BOOST_ASSERT(row < rows_);
1810         return row_info[row].descent_of_row;
1811 }
1812
1813
1814 int LyXTabular::getHeightOfTabular() const
1815 {
1816         int height = 0;
1817         for (row_type row = 0; row < rows_; ++row)
1818                 height += getAscentOfRow(row) + getDescentOfRow(row) +
1819                         getAdditionalHeight(row);
1820         return height;
1821 }
1822
1823
1824 bool LyXTabular::isPartOfMultiColumn(row_type row, col_type column) const
1825 {
1826         BOOST_ASSERT(row < rows_);
1827         BOOST_ASSERT(column < columns_);
1828         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
1829 }
1830
1831
1832 int LyXTabular::TeXTopHLine(odocstream & os, row_type row) const
1833 {
1834         // FIXME: assert or return 0 as in TeXBottomHLine()?
1835         BOOST_ASSERT(row != npos);
1836         BOOST_ASSERT(row < rows_);
1837
1838         idx_type const fcell = getFirstCellInRow(row);
1839         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1840         idx_type tmp = 0;
1841
1842         for (idx_type i = fcell; i < n; ++i) {
1843                 if (topLine(i))
1844                         ++tmp;
1845         }
1846         if (use_booktabs && row == 0) {
1847                 os << "\\toprule ";
1848         } else if (tmp == n - fcell) {
1849                 os << (use_booktabs ? "\\midrule " : "\\hline ");
1850         } else if (tmp) {
1851                 for (idx_type i = fcell; i < n; ++i) {
1852                         if (topLine(i)) {
1853                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1854                                    << column_of_cell(i) + 1
1855                                    << '-'
1856                                    << right_column_of_cell(i) + 1
1857                                    << "} ";
1858                         }
1859                 }
1860         } else {
1861                 return 0;
1862         }
1863         os << "\n";
1864         return 1;
1865 }
1866
1867
1868 int LyXTabular::TeXBottomHLine(odocstream & os, row_type row) const
1869 {
1870         // FIXME: return 0 or assert as in TeXTopHLine()?
1871         if (row == npos || row >= rows_)
1872                 return 0;
1873
1874         idx_type const fcell = getFirstCellInRow(row);
1875         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1876         idx_type tmp = 0;
1877
1878         for (idx_type i = fcell; i < n; ++i) {
1879                 if (bottomLine(i))
1880                         ++tmp;
1881         }
1882         if (use_booktabs && row == rows_ - 1) {
1883                 os << "\\bottomrule";
1884         } else if (tmp == n - fcell) {
1885                 os << (use_booktabs ? "\\midrule" : "\\hline");
1886         } else if (tmp) {
1887                 for (idx_type i = fcell; i < n; ++i) {
1888                         if (bottomLine(i)) {
1889                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1890                                    << column_of_cell(i) + 1
1891                                    << '-'
1892                                    << right_column_of_cell(i) + 1
1893                                    << "} ";
1894                         }
1895                 }
1896         } else {
1897                 return 0;
1898         }
1899         os << "\n";
1900         return 1;
1901 }
1902
1903
1904 int LyXTabular::TeXCellPreamble(odocstream & os, idx_type cell) const
1905 {
1906         int ret = 0;
1907
1908         if (getRotateCell(cell)) {
1909                 os << "\\begin{sideways}\n";
1910                 ++ret;
1911         }
1912         if (isMultiColumn(cell)) {
1913                 os << "\\multicolumn{" << cells_in_multicolumn(cell) << "}{";
1914                 if (!cellinfo_of_cell(cell).align_special.empty()) {
1915                         os << from_ascii(cellinfo_of_cell(cell).align_special)
1916                            << "}{";
1917                 } else {
1918                         if (leftLine(cell) &&
1919                                 (isFirstCellInRow(cell) ||
1920                                  (!isMultiColumn(cell - 1) && !leftLine(cell, true) &&
1921                                   !rightLine(cell - 1, true))))
1922                         {
1923                                 os << '|';
1924                         }
1925                         if (!getPWidth(cell).zero()) {
1926                                 switch (getVAlignment(cell)) {
1927                                 case LYX_VALIGN_TOP:
1928                                         os << 'p';
1929                                         break;
1930                                 case LYX_VALIGN_MIDDLE:
1931                                         os << 'm';
1932                                         break;
1933                                 case LYX_VALIGN_BOTTOM:
1934                                         os << 'b';
1935                                         break;
1936                                 }
1937                                 os << '{'
1938                                    << from_ascii(getPWidth(cell).asLatexString())
1939                                    << '}';
1940                         } else {
1941                                 switch (getAlignment(cell)) {
1942                                 case LYX_ALIGN_LEFT:
1943                                         os << 'l';
1944                                         break;
1945                                 case LYX_ALIGN_RIGHT:
1946                                         os << 'r';
1947                                         break;
1948                                 default:
1949                                         os << 'c';
1950                                         break;
1951                                 }
1952                         }
1953                         if (rightLine(cell))
1954                                 os << '|';
1955                         if (((cell + 1) < numberofcells) && !isFirstCellInRow(cell+1) &&
1956                                 leftLine(cell+1))
1957                                 os << '|';
1958                         os << "}{";
1959                 }
1960         }
1961         if (getUsebox(cell) == BOX_PARBOX) {
1962                 os << "\\parbox[";
1963                 switch (getVAlignment(cell)) {
1964                 case LYX_VALIGN_TOP:
1965                         os << 't';
1966                         break;
1967                 case LYX_VALIGN_MIDDLE:
1968                         os << 'c';
1969                         break;
1970                 case LYX_VALIGN_BOTTOM:
1971                         os << 'b';
1972                         break;
1973                 }
1974                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
1975                    << "}{";
1976         } else if (getUsebox(cell) == BOX_MINIPAGE) {
1977                 os << "\\begin{minipage}[";
1978                 switch (getVAlignment(cell)) {
1979                 case LYX_VALIGN_TOP:
1980                         os << 't';
1981                         break;
1982                 case LYX_VALIGN_MIDDLE:
1983                         os << 'm';
1984                         break;
1985                 case LYX_VALIGN_BOTTOM:
1986                         os << 'b';
1987                         break;
1988                 }
1989                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
1990                    << "}\n";
1991                 ++ret;
1992         }
1993         return ret;
1994 }
1995
1996
1997 int LyXTabular::TeXCellPostamble(odocstream & os, idx_type cell) const
1998 {
1999         int ret = 0;
2000
2001         // usual cells
2002         if (getUsebox(cell) == BOX_PARBOX)
2003                 os << '}';
2004         else if (getUsebox(cell) == BOX_MINIPAGE) {
2005                 os << "%\n\\end{minipage}";
2006                 ret += 2;
2007         }
2008         if (isMultiColumn(cell)) {
2009                 os << '}';
2010         }
2011         if (getRotateCell(cell)) {
2012                 os << "%\n\\end{sideways}";
2013                 ++ret;
2014         }
2015         return ret;
2016 }
2017
2018
2019 int LyXTabular::TeXLongtableHeaderFooter(odocstream & os, Buffer const & buf,
2020                                          OutputParams const & runparams) const
2021 {
2022         if (!is_long_tabular)
2023                 return 0;
2024
2025         int ret = 0;
2026         // output header info
2027         if (haveLTHead()) {
2028                 if (endhead.topDL) {
2029                         os << "\\hline\n";
2030                         ++ret;
2031                 }
2032                 for (row_type i = 0; i < rows_; ++i) {
2033                         if (row_info[i].endhead) {
2034                                 ret += TeXRow(os, i, buf, runparams);
2035                         }
2036                 }
2037                 if (endhead.bottomDL) {
2038                         os << "\\hline\n";
2039                         ++ret;
2040                 }
2041                 os << "\\endhead\n";
2042                 ++ret;
2043                 if (endfirsthead.empty) {
2044                         os << "\\endfirsthead\n";
2045                         ++ret;
2046                 }
2047         }
2048         // output firstheader info
2049         if (haveLTFirstHead()) {
2050                 if (endfirsthead.topDL) {
2051                         os << "\\hline\n";
2052                         ++ret;
2053                 }
2054                 for (row_type i = 0; i < rows_; ++i) {
2055                         if (row_info[i].endfirsthead) {
2056                                 ret += TeXRow(os, i, buf, runparams);
2057                         }
2058                 }
2059                 if (endfirsthead.bottomDL) {
2060                         os << "\\hline\n";
2061                         ++ret;
2062                 }
2063                 os << "\\endfirsthead\n";
2064                 ++ret;
2065         }
2066         // output footer info
2067         if (haveLTFoot()) {
2068                 if (endfoot.topDL) {
2069                         os << "\\hline\n";
2070                         ++ret;
2071                 }
2072                 for (row_type i = 0; i < rows_; ++i) {
2073                         if (row_info[i].endfoot) {
2074                                 ret += TeXRow(os, i, buf, runparams);
2075                         }
2076                 }
2077                 if (endfoot.bottomDL) {
2078                         os << "\\hline\n";
2079                         ++ret;
2080                 }
2081                 os << "\\endfoot\n";
2082                 ++ret;
2083                 if (endlastfoot.empty) {
2084                         os << "\\endlastfoot\n";
2085                         ++ret;
2086                 }
2087         }
2088         // output lastfooter info
2089         if (haveLTLastFoot()) {
2090                 if (endlastfoot.topDL) {
2091                         os << "\\hline\n";
2092                         ++ret;
2093                 }
2094                 for (row_type i = 0; i < rows_; ++i) {
2095                         if (row_info[i].endlastfoot) {
2096                                 ret += TeXRow(os, i, buf, runparams);
2097                         }
2098                 }
2099                 if (endlastfoot.bottomDL) {
2100                         os << "\\hline\n";
2101                         ++ret;
2102                 }
2103                 os << "\\endlastfoot\n";
2104                 ++ret;
2105         }
2106         return ret;
2107 }
2108
2109
2110 bool LyXTabular::isValidRow(row_type row) const
2111 {
2112         if (!is_long_tabular)
2113                 return true;
2114         return !row_info[row].endhead && !row_info[row].endfirsthead &&
2115                         !row_info[row].endfoot && !row_info[row].endlastfoot;
2116 }
2117
2118
2119 int LyXTabular::TeXRow(odocstream & os, row_type i, Buffer const & buf,
2120                        OutputParams const & runparams) const
2121 {
2122         idx_type cell = getCellNumber(i, 0);
2123         int ret = TeXTopHLine(os, i);
2124         if (row_info[i].top_space_default) {
2125                 if (use_booktabs)
2126                         os << "\\addlinespace\n";
2127                 else
2128                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2129         } else if(!row_info[i].top_space.zero()) {
2130                 if (use_booktabs)
2131                         os << "\\addlinespace["
2132                            << from_ascii(row_info[i].top_space.asLatexString())
2133                            << "]\n";
2134                 else {
2135                         os << "\\noalign{\\vskip"
2136                            << from_ascii(row_info[i].top_space.asLatexString())
2137                            << "}\n";
2138                 }
2139                 ++ret;
2140         }
2141         
2142         for (col_type j = 0; j < columns_; ++j) {
2143                 if (isPartOfMultiColumn(i, j))
2144                         continue;
2145                 ret += TeXCellPreamble(os, cell);
2146                 shared_ptr<InsetText> inset = getCellInset(cell);
2147
2148                 Paragraph const & par = inset->paragraphs().front();
2149                 bool rtl = par.isRightToLeftPar(buf.params())
2150                         && !par.empty()
2151                         && getPWidth(cell).zero();
2152
2153                 if (rtl)
2154                         os << "\\R{";
2155                 ret += inset->latex(buf, os, runparams);
2156                 if (rtl)
2157                         os << '}';
2158
2159                 ret += TeXCellPostamble(os, cell);
2160                 if (!isLastCellInRow(cell)) { // not last cell in row
2161                         os << " & ";
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                    << 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                            << from_ascii(row_info[i].interline_space.asLatexString())
2190                            << "]\n";
2191                 else
2192                         os << "\\noalign{\\vskip"
2193                            << 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 << 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                                    << 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, odocstream & 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, odocstream & 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(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         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(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         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, 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         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, 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                                 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                                 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 }
2736
2737
2738 } // namespace lyx