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