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