]> git.lyx.org Git - features.git/blob - src/tex2lyx/table.cpp
tex2lyx: tabular width in longtable is now possible (via xltabular).
[features.git] / src / tex2lyx / table.cpp
1 /**
2  * \file table.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  * \author Jean-Marc Lasgouttes
8  * \author Georg Baum
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 // {[(
14
15 #include <config.h>
16
17 #include "tex2lyx.h"
18
19 #include "Preamble.h"
20
21 #include "support/lassert.h"
22 #include "support/convert.h"
23 #include "support/lstrings.h"
24
25 #include <algorithm>
26 #include <iostream>
27 #include <sstream>
28 #include <vector>
29 #include <map>
30
31 using namespace std;
32
33 namespace lyx {
34
35
36 namespace {
37
38 class ColInfo {
39 public:
40         ColInfo() : align('n'), valign('n'), rightlines(0), leftlines(0), varwidth(false) {}
41         /// column alignment
42         char align;
43         /// vertical alignment
44         char valign;
45         /// column width
46         string width;
47         /// special column alignment
48         string special;
49         /// number of lines on the right
50         int rightlines;
51         /// number of lines on the left
52         int leftlines;
53         /// varwidth column
54         bool varwidth;
55 };
56
57
58 /// row type for longtables
59 enum LTRowType
60 {
61         /// normal row
62         LT_NORMAL,
63         /// part of head
64         LT_HEAD,
65         /// part of head on first page
66         LT_FIRSTHEAD,
67         /// part of foot
68         LT_FOOT,
69         /// part of foot on last page
70         LT_LASTFOOT
71 };
72
73
74 class RowInfo {
75 public:
76         RowInfo() : topline(false), bottomline(false), type(LT_NORMAL),
77                     caption(false), newpage(false) {}
78         /// Does this row have any special setting?
79         bool special() const
80         {
81                 return topline || bottomline || !top_space.empty() ||
82                         !bottom_space.empty() || !interline_space.empty() ||
83                         type != LT_NORMAL || caption || newpage;
84         }
85         /// horizontal line above
86         bool topline;
87         /// horizontal line below
88         bool bottomline;
89         /// Extra space between the top line and this row
90         string top_space;
91         /// Extra space between this row and the bottom line
92         string bottom_space;
93         /// Extra space between the bottom line and the next top line
94         string interline_space;
95         /// These are for longtabulars only
96         /// row type (head, foot, firsthead etc.)
97         LTRowType type;
98         /// row for a caption
99         bool caption;
100         /// row for a newpage
101         bool newpage;
102 };
103
104
105 /// the numeric values are part of the file format!
106 enum Multi {
107         /// A normal cell
108         CELL_NORMAL = 0,
109         /// A multicolumn cell. The number of columns is <tt>1 + number
110         /// of CELL_PART_OF_MULTICOLUMN cells</tt> that follow directly
111         CELL_BEGIN_OF_MULTICOLUMN,
112         /// This is a dummy cell (part of a multicolumn cell)
113         CELL_PART_OF_MULTICOLUMN,
114         ///
115         CELL_BEGIN_OF_MULTIROW,
116         ///
117         CELL_PART_OF_MULTIROW
118 };
119
120
121 class CellInfo {
122 public:
123         CellInfo() : multi(CELL_NORMAL), align('n'), valign('n'),
124                      leftlines(0), rightlines(0), topline(false),
125                      bottomline(false), rotate(0), mrxnum(0) {}
126         /// cell content
127         string content;
128         /// multicolumn flag
129         Multi multi;
130         /// cell alignment
131         char align;
132         /// vertical cell alignment
133         char valign;
134         /// number of lines on the left
135         int leftlines;
136         /// number of lines on the right
137         int rightlines;
138         /// do we have a line above?
139         bool topline;
140         /// do we have a line below?
141         bool bottomline;
142         /// how is the cell rotated?
143         int rotate;
144         /// width for multicolumn cells
145         string width;
146         /// special formatting for multicolumn cells
147         string special;
148         /// multirow offset
149         string mroffset;
150         /// number of further multirows
151         int mrxnum;
152 };
153
154
155 class ltType {
156 public:
157         // constructor
158         ltType() : set(false), topDL(false), bottomDL(false), empty(false) {}
159         // we have this header type (is set in the getLT... functions)
160         bool set;
161         // double borders on top
162         bool topDL;
163         // double borders on bottom
164         bool bottomDL;
165         // used for FirstHeader & LastFooter and if this is true
166         // all the rows marked as FirstHeader or LastFooter are
167         // ignored in the output and it is set to be empty!
168         bool empty;
169 };
170
171
172 /// translate a horizontal alignment (as stored in ColInfo and CellInfo) to LyX
173 inline char const * verbose_align(char c)
174 {
175         switch (c) {
176         case 'c':
177                 return "center";
178         case 'r':
179                 return "right";
180         case 'l':
181                 return "left";
182         default:
183                 return "none";
184         }
185 }
186
187
188 /// translate a vertical alignment (as stored in ColInfo and CellInfo) to LyX
189 inline char const * verbose_valign(char c)
190 {
191         // The default value for no special alignment is "top".
192         switch (c) {
193         case 'm':
194                 return "middle";
195         case 'b':
196                 return "bottom";
197         case 'p':
198         default:
199                 return "top";
200         }
201 }
202
203
204 // stripped down from tabluar.C. We use it currently only for bools and
205 // strings
206 string const write_attribute(string const & name, bool const & b)
207 {
208         // we write only true attribute values so we remove a bit of the
209         // file format bloat for tabulars.
210         return b ? ' ' + name + "=\"true\"" : string();
211 }
212
213
214 string const write_attribute(string const & name, string const & s)
215 {
216         return s.empty() ? string() : ' ' + name + "=\"" + s + '"';
217 }
218
219
220 string const write_attribute(string const & name, int const & i)
221 {
222         // we write only true attribute values so we remove a bit of the
223         // file format bloat for tabulars.
224         return i ? write_attribute(name, convert<string>(i)) : string();
225 }
226
227
228 /*! rather brutish way to code table structure in a string:
229
230 \verbatim
231   \begin{tabular}{ccc}
232     1 & 2 & 3\\ \hline
233     \multicolumn{2}{c}{4} & 5 //
234     6 & 7 \\
235     8 \endhead
236   \end{tabular}
237 \endverbatim
238
239  gets "translated" to:
240
241 \verbatim
242          HLINE 1                     TAB 2 TAB 3 HLINE          HLINE LINE
243   \hline HLINE \multicolumn{2}{c}{4} TAB 5       HLINE          HLINE LINE
244          HLINE 6                     TAB 7       HLINE          HLINE LINE
245          HLINE 8                                 HLINE \endhead HLINE LINE
246 \endverbatim
247  */
248
249 char const TAB   = '\001';
250 char const LINE  = '\002';
251 char const HLINE = '\004';
252
253
254 /*!
255  * Move the information in leftlines, rightlines, align and valign to the
256  * special field. This is necessary if the special field is not empty,
257  * because LyX ignores leftlines > 1, rightlines > 1, align and valign in
258  * this case.
259  */
260 void ci2special(ColInfo & ci)
261 {
262         if (ci.width.empty() && ci.align == 'n')
263                 // The alignment setting is already in special, since
264                 // handle_colalign() never stores ci with these settings
265                 // and ensures that leftlines == 0 and rightlines == 0 in
266                 // this case.
267                 return;
268
269         if (!ci.width.empty()) {
270                 string arraybackslash;
271                 if (ci.varwidth)
272                         arraybackslash = "\\arraybackslash";
273                 switch (ci.align) {
274                 case 'l':
275                         ci.special += ">{\\raggedright" + arraybackslash + "}";
276                         break;
277                 case 'r':
278                         ci.special += ">{\\raggedleft" + arraybackslash + "}";
279                         break;
280                 case 'c':
281                         ci.special += ">{\\centering" + arraybackslash + "}";
282                         break;
283                 }
284                 if (ci.varwidth)
285                         ci.special += 'X';
286                 else if (ci.valign == 'n')
287                         ci.special += 'p';
288                 else
289                         ci.special += ci.valign;
290                 ci.special += '{' + ci.width + '}';
291                 ci.width.erase();
292         } else
293                 ci.special += ci.align;
294
295         // LyX can only have one left and one right line.
296         for (int i = 1; i < ci.leftlines; ++i)
297                 ci.special.insert(0, "|");
298         for (int i = 1; i < ci.rightlines; ++i)
299                 ci.special += '|';
300         ci.leftlines = min(ci.leftlines, 1);
301         ci.rightlines = min(ci.rightlines, 1);
302         ci.align = 'n';
303         ci.valign = 'n';
304 }
305
306
307 /*!
308  * Handle column specifications for tabulars and multicolumns.
309  * The next token of the parser \p p must be an opening brace, and we read
310  * everything until the matching closing brace.
311  * The resulting column specifications are filled into \p colinfo. This is
312  * in an intermediate form. fix_colalign() makes it suitable for LyX output.
313  */
314 void handle_colalign(Parser & p, vector<ColInfo> & colinfo,
315                      ColInfo const & start)
316 {
317         if (p.get_token().cat() != catBegin)
318                 cerr << "Wrong syntax for table column alignment.\n"
319                         "Expected '{', got '" << p.curr_token().asInput()
320                      << "'.\n";
321
322         ColInfo next = start;
323         for (Token t = p.get_token(); p.good() && t.cat() != catEnd;
324              t = p.get_token()) {
325 #ifdef FILEDEBUG
326                 cerr << "t: " << t << "  c: '" << t.character() << "'\n";
327 #endif
328
329                 // We cannot handle comments here
330                 if (t.cat() == catComment) {
331                         if (t.cs().empty()) {
332                                 // "%\n" combination
333                                 p.skip_spaces();
334                         } else
335                                 cerr << "Ignoring comment: " << t.asInput();
336                         continue;
337                 }
338
339                 switch (t.character()) {
340                         case ' ':
341                                 // whitespace, ignore.
342                                 break;
343                         case 'c':
344                         case 'l':
345                         case 'r':
346                                 // new column, horizontal aligned
347                                 next.align = t.character();
348                                 if (!next.special.empty())
349                                         ci2special(next);
350                                 colinfo.push_back(next);
351                                 next = ColInfo();
352                                 break;
353                         case 'X':
354                                 // varwidth column
355                                 next.varwidth = true;
356                                 if (!next.special.empty())
357                                         ci2special(next);
358                                 colinfo.push_back(next);
359                                 next = ColInfo();
360                                 break;
361                         case 'p':
362                         case 'b':
363                         case 'm':
364                                 // new column, vertical aligned box
365                                 next.valign = t.character();
366                                 next.width = p.verbatim_item();
367                                 if (!next.special.empty())
368                                         ci2special(next);
369                                 colinfo.push_back(next);
370                                 next = ColInfo();
371                                 break;
372                         case '|':
373                                 // vertical rule
374                                 if (colinfo.empty()) {
375                                         if (next.special.empty())
376                                                 ++next.leftlines;
377                                         else
378                                                 next.special += '|';
379                                 } else if (colinfo.back().special.empty())
380                                         ++colinfo.back().rightlines;
381                                 else if (next.special.empty())
382                                         ++next.leftlines;
383                                 else
384                                         colinfo.back().special += '|';
385                                 break;
386                         case '>': {
387                                 // text before the next column
388                                 string const s = trimSpaceAndEol(p.verbatim_item());
389                                 if (next.special.empty() &&
390                                     next.align == 'n') {
391                                         // Maybe this can be converted to a
392                                         // horizontal alignment setting for
393                                         // fixed width columns
394                                         if (s == "\\raggedleft" || s == "\\raggedleft\\arraybackslash")
395                                                 next.align = 'r';
396                                         else if (s == "\\raggedright" || s == "\\raggedright\\arraybackslash")
397                                                 next.align = 'l';
398                                         else if (s == "\\centering" || s == "\\centering\\arraybackslash")
399                                                 next.align = 'c';
400                                         else
401                                                 next.special = ">{" + s + '}';
402                                 } else
403                                         next.special += ">{" + s + '}';
404                                 break;
405                         }
406                         case '<': {
407                                 // text after the last column
408                                 string const s = trimSpaceAndEol(p.verbatim_item());
409                                 if (colinfo.empty())
410                                         // This is not possible in LaTeX.
411                                         cerr << "Ignoring separator '<{"
412                                              << s << "}'." << endl;
413                                 else {
414                                         ColInfo & ci = colinfo.back();
415                                         ci2special(ci);
416                                         ci.special += "<{" + s + '}';
417                                 }
418                                 break;
419                         }
420                         case '*': {
421                                 if (p.next_token().character() != '{')
422                                         continue;
423                                 // *{n}{arg} means 'n' columns of type 'arg'
424                                 string const num = p.verbatim_item();
425                                 string const arg = p.verbatim_item();
426                                 size_t const n = convert<unsigned int>(num);
427                                 if (!arg.empty() && n > 0) {
428                                         string s("{");
429                                         for (size_t i = 0; i < n; ++i)
430                                                 s += arg;
431                                         s += '}';
432                                         Parser p2(s);
433                                         handle_colalign(p2, colinfo, next);
434                                         next = ColInfo();
435                                 } else {
436                                         cerr << "Ignoring column specification"
437                                                 " '*{" << num << "}{"
438                                              << arg << "}'." << endl;
439                                 }
440                                 break;
441                         }
442                         case '@':
443                                 // text instead of the column spacing
444                         case '!':
445                                 // text in addition to the column spacing
446                                 next.special += t.character();
447                                 next.special += '{' + p.verbatim_item() + '}';
448                                 break;
449                         default: {
450                                 // try user defined column types
451                                 // unknown column types (nargs == -1) are
452                                 // assumed to consume no arguments
453                                 ci2special(next);
454                                 next.special += t.character();
455                                 int const nargs =
456                                         preamble.getSpecialTableColumnArguments(t.character());
457                                 for (int i = 0; i < nargs; ++i)
458                                         next.special += '{' +
459                                                 p.verbatim_item() + '}';
460                                 colinfo.push_back(next);
461                                 next = ColInfo();
462                                 break;
463                         }
464                         }
465         }
466
467         // Maybe we have some column separators that need to be added to the
468         // last column?
469         ci2special(next);
470         if (!next.special.empty()) {
471                 ColInfo & ci = colinfo.back();
472                 ci2special(ci);
473                 ci.special += next.special;
474                 next.special.erase();
475         }
476 }
477
478
479 /*!
480  * Move the left and right lines and alignment settings of the column \p ci
481  * to the special field if necessary.
482  */
483 void fix_colalign(ColInfo & ci)
484 {
485         if (ci.leftlines > 1 || ci.rightlines > 1)
486                 ci2special(ci);
487 }
488
489
490 /*!
491  * LyX can't handle more than one vertical line at the left or right side
492  * of a column.
493  * This function moves the left and right lines and alignment settings of all
494  * columns in \p colinfo to the special field if necessary.
495  */
496 void fix_colalign(vector<ColInfo> & colinfo)
497 {
498         // Try to move extra leftlines to the previous column.
499         // We do this only if both special fields are empty, otherwise we
500         // can't tell wether the result will be the same.
501         for (size_t col = 0; col < colinfo.size(); ++col) {
502                 if (colinfo[col].leftlines > 1 &&
503                     colinfo[col].special.empty() && col > 0 &&
504                     colinfo[col - 1].rightlines == 0 &&
505                     colinfo[col - 1].special.empty()) {
506                         ++colinfo[col - 1].rightlines;
507                         --colinfo[col].leftlines;
508                 }
509         }
510         // Try to move extra rightlines to the next column
511         for (size_t col = 0; col < colinfo.size(); ++col) {
512                 if (colinfo[col].rightlines > 1 &&
513                     colinfo[col].special.empty() &&
514                     col < colinfo.size() - 1 &&
515                     colinfo[col + 1].leftlines == 0 &&
516                     colinfo[col + 1].special.empty()) {
517                         ++colinfo[col + 1].leftlines;
518                         --colinfo[col].rightlines;
519                 }
520         }
521         // Move the lines and alignment settings to the special field if
522         // necessary
523         for (size_t col = 0; col < colinfo.size(); ++col)
524                 fix_colalign(colinfo[col]);
525 }
526
527
528 /*!
529  * Parse hlines and similar stuff.
530  * \returns wether the token \p t was parsed
531  */
532 bool parse_hlines(Parser & p, Token const & t, string & hlines,
533                   bool is_long_tabular)
534 {
535         LASSERT(t.cat() == catEscape, return false);
536
537         if (t.cs() == "hline" || t.cs() == "toprule" || t.cs() == "midrule" ||
538             t.cs() == "bottomrule")
539                 hlines += '\\' + t.cs();
540
541         else if (t.cs() == "cline")
542                 hlines += "\\cline{" + p.verbatim_item() + '}';
543
544         else if (t.cs() == "cmidrule") {
545                 // We cannot handle the \cmidrule(l){3-4} form
546                 p.pushPosition();
547                 p.skip_spaces(true);
548                 bool const hasParentheses(p.getFullArg('(', ')').first);
549                 p.popPosition();
550                 if (hasParentheses)
551                         return false;
552                 hlines += "\\cmidrule{" + p.verbatim_item() + '}';
553         }
554
555         else if (t.cs() == "addlinespace") {
556                 p.pushPosition();
557                 p.skip_spaces(true);
558                 bool const hasArgument(p.getFullArg('{', '}').first);
559                 p.popPosition();
560                 if (hasArgument)
561                         hlines += "\\addlinespace{" + p.verbatim_item() + '}';
562                 else
563                         hlines += "\\addlinespace";
564         }
565
566         else if (is_long_tabular && t.cs() == "newpage")
567                 hlines += "\\newpage";
568
569         else
570                 return false;
571
572         return true;
573 }
574
575
576 /// Position in a row
577 enum RowPosition {
578         /// At the very beginning, before the first token
579         ROW_START,
580         /// After the first token and before any column token
581         IN_HLINES_START,
582         /// After the first column token. Comments and whitespace are only
583         /// treated as tokens in this position
584         IN_COLUMNS,
585         /// After the first non-column token at the end
586         IN_HLINES_END
587 };
588
589
590 /*!
591  * Parse table structure.
592  * We parse tables in a two-pass process: This function extracts the table
593  * structure (rows, columns, hlines etc.), but does not change the cell
594  * content. The cell content is parsed in a second step in handle_tabular().
595  */
596 void parse_table(Parser & p, ostream & os, bool is_long_tabular,
597                  RowPosition & pos, unsigned flags)
598 {
599         // table structure commands such as \hline
600         string hlines;
601
602         // comments that occur at places where we can't handle them
603         string comments;
604
605         while (p.good()) {
606                 Token const & t = p.get_token();
607
608 #ifdef FILEDEBUG
609                 debugToken(cerr, t, flags);
610 #endif
611
612                 // comments and whitespace in hlines
613                 switch (pos) {
614                 case ROW_START:
615                 case IN_HLINES_START:
616                 case IN_HLINES_END:
617                         if (t.cat() == catComment) {
618                                 if (t.cs().empty())
619                                         // line continuation
620                                         p.skip_spaces();
621                                 else
622                                         // We can't handle comments here,
623                                         // store them for later use
624                                         comments += t.asInput();
625                                 continue;
626                         } else if (t.cat() == catSpace ||
627                                    t.cat() == catNewline) {
628                                 // whitespace is irrelevant here, we
629                                 // need to recognize hline stuff
630                                 p.skip_spaces();
631                                 continue;
632                         }
633                         break;
634                 case IN_COLUMNS:
635                         break;
636                 }
637
638                 // We need to handle structure stuff first in order to
639                 // determine wether we need to output a HLINE separator
640                 // before the row or not.
641                 if (t.cat() == catEscape) {
642                         if (parse_hlines(p, t, hlines, is_long_tabular)) {
643                                 switch (pos) {
644                                 case ROW_START:
645                                         pos = IN_HLINES_START;
646                                         break;
647                                 case IN_COLUMNS:
648                                         pos = IN_HLINES_END;
649                                         break;
650                                 case IN_HLINES_START:
651                                 case IN_HLINES_END:
652                                         break;
653                                 }
654                                 continue;
655                         }
656
657                         else if (t.cs() == "tabularnewline" ||
658                                  t.cs() == "\\" ||
659                                  t.cs() == "cr") {
660                                 if (t.cs() == "cr")
661                                         cerr << "Warning: Converting TeX "
662                                                 "'\\cr' to LaTeX '\\\\'."
663                                              << endl;
664                                 // stuff before the line break
665                                 os << comments << HLINE << hlines << HLINE
666                                    << LINE;
667                                 //cerr << "hlines: " << hlines << endl;
668                                 hlines.erase();
669                                 comments.erase();
670                                 pos = ROW_START;
671                                 continue;
672                         }
673
674                         else if (is_long_tabular &&
675                                  (t.cs() == "endhead" ||
676                                   t.cs() == "endfirsthead" ||
677                                   t.cs() == "endfoot" ||
678                                   t.cs() == "endlastfoot")) {
679                                 hlines += t.asInput();
680                                 switch (pos) {
681                                 case IN_COLUMNS:
682                                 case IN_HLINES_END:
683                                         // these commands are implicit line
684                                         // breaks
685                                         os << comments << HLINE << hlines
686                                            << HLINE << LINE;
687                                         hlines.erase();
688                                         comments.erase();
689                                         pos = ROW_START;
690                                         break;
691                                 case ROW_START:
692                                         pos = IN_HLINES_START;
693                                         break;
694                                 case IN_HLINES_START:
695                                         break;
696                                 }
697                                 continue;
698                         }
699                 }
700
701                 // We need a HLINE separator if we either have no hline
702                 // stuff at all and are just starting a row or if we just
703                 // got the first non-hline token.
704                 switch (pos) {
705                 case ROW_START:
706                         // no hline tokens exist, first token at row start
707                 case IN_HLINES_START:
708                         // hline tokens exist, first non-hline token at row
709                         // start
710                         os << hlines << HLINE << comments;
711                         hlines.erase();
712                         comments.erase();
713                         pos = IN_COLUMNS;
714                         break;
715                 case IN_HLINES_END:
716                         // Oops, there is still cell content or unsupported
717                         // booktabs commands after hline stuff. The latter are
718                         // moved to the cell, and the first does not work in
719                         // LaTeX, so we ignore the hlines.
720                         os << comments;
721                         comments.erase();
722                         if (support::contains(hlines, "\\hline") ||
723                             support::contains(hlines, "\\cline") ||
724                             support::contains(hlines, "\\newpage"))
725                                 cerr << "Ignoring '" << hlines
726                                      << "' in a cell" << endl;
727                         else
728                                 os << hlines;
729                         hlines.erase();
730                         pos = IN_COLUMNS;
731                         break;
732                 case IN_COLUMNS:
733                         break;
734                 }
735
736                 // If we come here we have normal cell content
737                 //
738                 // cat codes
739                 //
740                 if (t.cat() == catMath) {
741                         // we are inside some text mode thingy, so opening new math is allowed
742                         Token const & n = p.get_token();
743                         if (n.cat() == catMath) {
744                                 // TeX's $$...$$ syntax for displayed math
745                                 os << "\\[";
746                                 // This does only work because parse_math outputs TeX
747                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
748                                 os << "\\]";
749                                 p.get_token(); // skip the second '$' token
750                         } else {
751                                 // simple $...$  stuff
752                                 p.putback();
753                                 os << '$';
754                                 // This does only work because parse_math outputs TeX
755                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
756                                 os << '$';
757                         }
758                 }
759
760                 else if (t.cat() == catSpace
761                          || t.cat() == catNewline
762                          || t.cat() == catLetter
763                          || t.cat() == catSuper
764                          || t.cat() == catSub
765                          || t.cat() == catOther
766                          || t.cat() == catActive
767                          || t.cat() == catParameter)
768                         os << t.cs();
769
770                 else if (t.cat() == catBegin) {
771                         os << '{';
772                         parse_table(p, os, is_long_tabular, pos,
773                                     FLAG_BRACE_LAST);
774                         os << '}';
775                 }
776
777                 else if (t.cat() == catEnd) {
778                         if (flags & FLAG_BRACE_LAST)
779                                 return;
780                         cerr << "unexpected '}'\n";
781                 }
782
783                 else if (t.cat() == catAlign) {
784                         os << TAB;
785                         p.skip_spaces();
786                 }
787
788                 else if (t.cat() == catComment)
789                         os << t.asInput();
790
791                 else if (t.cs() == "(") {
792                         os << "\\(";
793                         // This does only work because parse_math outputs TeX
794                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
795                         os << "\\)";
796                 }
797
798                 else if (t.cs() == "[") {
799                         os << "\\[";
800                         // This does only work because parse_math outputs TeX
801                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
802                         os << "\\]";
803                 }
804
805                 else if (t.cs() == "begin") {
806                         string const name = p.getArg('{', '}');
807                         active_environments.push_back(name);
808                         os << "\\begin{" << name << '}';
809                         // treat the nested environment as a block, don't
810                         // parse &, \\ etc, because they don't belong to our
811                         // table if they appear.
812                         os << p.ertEnvironment(name);
813                         os << "\\end{" << name << '}';
814                         active_environments.pop_back();
815                 }
816
817                 else if (t.cs() == "end") {
818                         if (flags & FLAG_END) {
819                                 // eat environment name
820                                 string const name = p.getArg('{', '}');
821                                 if (name != active_environment())
822                                         p.error("\\end{" + name + "} does not match \\begin{"
823                                                 + active_environment() + "}");
824                                 return;
825                         }
826                         p.error("found 'end' unexpectedly");
827                 }
828
829                 else
830                         os << t.asInput();
831         }
832
833         // We can have comments if the last line is incomplete
834         os << comments;
835
836         // We can have hline stuff if the last line is incomplete
837         if (!hlines.empty()) {
838                 // this does not work in LaTeX, so we ignore it
839                 cerr << "Ignoring '" << hlines << "' at end of tabular"
840                      << endl;
841         }
842 }
843
844
845 void handle_hline_above(RowInfo & ri, vector<CellInfo> & ci)
846 {
847         ri.topline = true;
848         for (size_t col = 0; col < ci.size(); ++col)
849                 ci[col].topline = true;
850 }
851
852
853 void handle_hline_below(RowInfo & ri, vector<CellInfo> & ci)
854 {
855         ri.bottomline = true;
856         for (size_t col = 0; col < ci.size(); ++col)
857                 ci[col].bottomline = true;
858 }
859
860
861 } // anonymous namespace
862
863
864 void handle_tabular(Parser & p, ostream & os, string const & name,
865                     string const & tabularwidth, string const & halign,
866                     Context & context)
867 {
868         bool const is_long_tabular(name == "longtable" || name == "xltabular");
869         bool booktabs = false;
870         string tabularvalignment("middle");
871         string posopts = p.getOpt();
872         if (!posopts.empty()) {
873                 if (posopts == "[t]")
874                         tabularvalignment = "top";
875                 else if (posopts == "[b]")
876                         tabularvalignment = "bottom";
877                 else
878                         cerr << "vertical tabular positioning '"
879                              << posopts << "' ignored\n";
880         }
881
882         vector<ColInfo> colinfo;
883
884         // handle column formatting
885         handle_colalign(p, colinfo, ColInfo());
886         fix_colalign(colinfo);
887
888         // first scan of cells
889         // use table mode to keep it minimal-invasive
890         // not exactly what's TeX doing...
891         vector<string> lines;
892         ostringstream ss;
893         RowPosition rowpos = ROW_START;
894         parse_table(p, ss, is_long_tabular, rowpos, FLAG_END);
895         split(ss.str(), lines, LINE);
896
897         vector< vector<CellInfo> > cellinfo(lines.size());
898         vector<RowInfo> rowinfo(lines.size());
899         ltType endfirsthead;
900         ltType endhead;
901         ltType endfoot;
902         ltType endlastfoot;
903
904         // split into rows
905         //cerr << "// split into rows\n";
906         for (size_t row = 0; row < rowinfo.size();) {
907
908                 // init row
909                 cellinfo[row].resize(colinfo.size());
910                 bool deletelastrow = false;
911
912                 // split row
913                 vector<string> dummy;
914                 //cerr << "\n########### LINE: " << lines[row] << "########\n";
915                 split(lines[row], dummy, HLINE);
916
917                 // handle horizontal line fragments
918                 // we do only expect this for a last line without '\\'
919                 if (dummy.size() != 3) {
920                         if ((dummy.size() != 1 && dummy.size() != 2) ||
921                             row != rowinfo.size() - 1)
922                                 cerr << "unexpected dummy size: " << dummy.size()
923                                         << " content: " << lines[row] << "\n";
924                         dummy.resize(3);
925                 }
926                 lines[row] = dummy[1];
927
928                 //cerr << "line: " << row << " above 0: " << dummy[0] << "\n";
929                 //cerr << "line: " << row << " below 2: " << dummy[2] <<  "\n";
930                 //cerr << "line: " << row << " cells 1: " << dummy[1] <<  "\n";
931
932                 for (int i = 0; i <= 2; i += 2) {
933                         //cerr << "   reading from line string '" << dummy[i] << "'\n";
934                         Parser p1(dummy[i]);
935                         while (p1.good()) {
936                                 Token t = p1.get_token();
937                                 //cerr << "read token: " << t << "\n";
938                                 if (t.cs() == "hline" || t.cs() == "toprule" ||
939                                     t.cs() == "midrule" ||
940                                     t.cs() == "bottomrule") {
941                                         if (t.cs() != "hline")
942                                                 booktabs = true;
943                                         if (i == 0) {
944                                                 if (rowinfo[row].topline) {
945                                                         if (row > 0) // extra bottomline above
946                                                                 handle_hline_below(rowinfo[row - 1], cellinfo[row - 1]);
947                                                         else
948                                                                 cerr << "dropping extra "
949                                                                      << t.cs() << '\n';
950                                                         //cerr << "below row: " << row-1 << endl;
951                                                 } else {
952                                                         handle_hline_above(rowinfo[row], cellinfo[row]);
953                                                         //cerr << "above row: " << row << endl;
954                                                 }
955                                         } else {
956                                                 //cerr << "below row: " << row << endl;
957                                                 handle_hline_below(rowinfo[row], cellinfo[row]);
958                                         }
959                                 } else if (t.cs() == "cline" || t.cs() == "cmidrule") {
960                                         if (t.cs() == "cmidrule")
961                                                 booktabs = true;
962                                         string arg = p1.verbatim_item();
963                                         //cerr << "read " << t.cs() << " arg: '" << arg << "'\n";
964                                         vector<string> cols;
965                                         split(arg, cols, '-');
966                                         cols.resize(2);
967                                         size_t from = convert<unsigned int>(cols[0]);
968                                         if (from == 0)
969                                                 cerr << "Could not parse "
970                                                      << t.cs() << " start column."
971                                                      << endl;
972                                         else
973                                                 // 1 based index -> 0 based
974                                                 --from;
975                                         if (from >= colinfo.size()) {
976                                                 cerr << t.cs() << " starts at "
977                                                         "non existing column "
978                                                      << (from + 1) << endl;
979                                                 from = colinfo.size() - 1;
980                                         }
981                                         size_t to = convert<unsigned int>(cols[1]);
982                                         if (to == 0)
983                                                 cerr << "Could not parse "
984                                                      << t.cs() << " end column."
985                                                      << endl;
986                                         else
987                                                 // 1 based index -> 0 based
988                                                 --to;
989                                         if (to >= colinfo.size()) {
990                                                 cerr << t.cs() << " ends at "
991                                                         "non existing column "
992                                                      << (to + 1) << endl;
993                                                 to = colinfo.size() - 1;
994                                         }
995                                         for (size_t col = from; col <= to; ++col) {
996                                                 //cerr << "row: " << row << " col: " << col << " i: " << i << endl;
997                                                 if (i == 0) {
998                                                         rowinfo[row].topline = true;
999                                                         cellinfo[row][col].topline = true;
1000                                                 } else {
1001                                                         rowinfo[row].bottomline = true;
1002                                                         cellinfo[row][col].bottomline = true;
1003                                                 }
1004                                         }
1005                                 } else if (t.cs() == "addlinespace") {
1006                                         booktabs = true;
1007                                         string const opt = p.next_token().cat() == catBegin ?
1008                                                         p.verbatim_item() : string();
1009                                         if (i == 0) {
1010                                                 if (opt.empty())
1011                                                         rowinfo[row].top_space = "default";
1012                                                 else
1013                                                         rowinfo[row].top_space = translate_len(opt);
1014                                         } else if (rowinfo[row].bottomline) {
1015                                                 if (opt.empty())
1016                                                         rowinfo[row].bottom_space = "default";
1017                                                 else
1018                                                         rowinfo[row].bottom_space = translate_len(opt);
1019                                         } else {
1020                                                 if (opt.empty())
1021                                                         rowinfo[row].interline_space = "default";
1022                                                 else
1023                                                         rowinfo[row].interline_space = translate_len(opt);
1024                                         }
1025                                 } else if (t.cs() == "endhead") {
1026                                         if (i == 0)
1027                                                 endhead.empty = true;
1028                                         else
1029                                                 rowinfo[row].type = LT_HEAD;
1030                                         for (int r = row - 1; r >= 0; --r) {
1031                                                 if (rowinfo[r].type != LT_NORMAL)
1032                                                         break;
1033                                                 rowinfo[r].type = LT_HEAD;
1034                                                 endhead.empty = false;
1035                                         }
1036                                         endhead.set = true;
1037                                 } else if (t.cs() == "endfirsthead") {
1038                                         if (i == 0)
1039                                                 endfirsthead.empty = true;
1040                                         else
1041                                                 rowinfo[row].type = LT_FIRSTHEAD;
1042                                         for (int r = row - 1; r >= 0; --r) {
1043                                                 if (rowinfo[r].type != LT_NORMAL)
1044                                                         break;
1045                                                 rowinfo[r].type = LT_FIRSTHEAD;
1046                                                 endfirsthead.empty = false;
1047                                         }
1048                                         endfirsthead.set = true;
1049                                 } else if (t.cs() == "endfoot") {
1050                                         if (i == 0)
1051                                                 endfoot.empty = true;
1052                                         else
1053                                                 rowinfo[row].type = LT_FOOT;
1054                                         for (int r = row - 1; r >= 0; --r) {
1055                                                 if (rowinfo[r].type != LT_NORMAL)
1056                                                         break;
1057                                                 rowinfo[r].type = LT_FOOT;
1058                                                 endfoot.empty = false;
1059                                         }
1060                                         endfoot.set = true;
1061                                 } else if (t.cs() == "endlastfoot") {
1062                                         if (i == 0)
1063                                                 endlastfoot.empty = true;
1064                                         else
1065                                                 rowinfo[row].type = LT_LASTFOOT;
1066                                         for (int r = row - 1; r >= 0; --r) {
1067                                                 if (rowinfo[r].type != LT_NORMAL)
1068                                                         break;
1069                                                 rowinfo[r].type = LT_LASTFOOT;
1070                                                 endlastfoot.empty = false;
1071                                         }
1072                                         endlastfoot.set = true;
1073                                 } else if (t.cs() == "newpage") {
1074                                         if (i == 0) {
1075                                                 if (row > 0)
1076                                                         rowinfo[row - 1].newpage = true;
1077                                                 else
1078                                                         // This does not work in LaTeX
1079                                                         cerr << "Ignoring "
1080                                                                 "'\\newpage' "
1081                                                                 "before rows."
1082                                                              << endl;
1083                                         } else
1084                                                 rowinfo[row].newpage = true;
1085                                 } else {
1086                                         cerr << "unexpected line token: " << t << endl;
1087                                 }
1088                         }
1089                 }
1090
1091                 // LyX ends headers and footers always with \tabularnewline.
1092                 // This causes one additional row in the output.
1093                 // If the last row of a header/footer is empty, we can work
1094                 // around that by removing it.
1095                 if (row > 1) {
1096                         RowInfo test = rowinfo[row-1];
1097                         test.type = LT_NORMAL;
1098                         if (lines[row-1].empty() && !test.special()) {
1099                                 switch (rowinfo[row-1].type) {
1100                                 case LT_FIRSTHEAD:
1101                                         if (rowinfo[row].type != LT_FIRSTHEAD &&
1102                                             rowinfo[row-2].type == LT_FIRSTHEAD)
1103                                                 deletelastrow = true;
1104                                         break;
1105                                 case LT_HEAD:
1106                                         if (rowinfo[row].type != LT_HEAD &&
1107                                             rowinfo[row-2].type == LT_HEAD)
1108                                                 deletelastrow = true;
1109                                         break;
1110                                 case LT_FOOT:
1111                                         if (rowinfo[row].type != LT_FOOT &&
1112                                             rowinfo[row-2].type == LT_FOOT)
1113                                                 deletelastrow = true;
1114                                         break;
1115                                 case LT_LASTFOOT:
1116                                         if (rowinfo[row].type != LT_LASTFOOT &&
1117                                             rowinfo[row-2].type == LT_LASTFOOT)
1118                                                 deletelastrow = true;
1119                                         break;
1120                                 case LT_NORMAL:
1121                                         break;
1122                                 }
1123                         }
1124                 }
1125
1126                 if (deletelastrow) {
1127                         lines.erase(lines.begin() + (row - 1));
1128                         rowinfo.erase(rowinfo.begin() + (row - 1));
1129                         cellinfo.erase(cellinfo.begin() + (row - 1));
1130                         continue;
1131                 }
1132
1133                 // split into cells
1134                 vector<string> cells;
1135                 split(lines[row], cells, TAB);
1136                 for (size_t col = 0, cell = 0; cell < cells.size();
1137                      ++col, ++cell) {
1138                         //cerr << "cell content: '" << cells[cell] << "'\n";
1139                         if (col >= colinfo.size()) {
1140                                 // This does not work in LaTeX
1141                                 cerr << "Ignoring extra cell '"
1142                                      << cells[cell] << "'." << endl;
1143                                 continue;
1144                         }
1145                         Parser parse(cells[cell]);
1146                         parse.skip_spaces();
1147                         //cells[cell] << "'\n";
1148                         if (parse.next_token().cs() == "multirow") {
1149                                 // We do not support the vpos arg yet.
1150                                 if (parse.hasOpt()) {
1151                                         string const vpos = parse.getArg('[', ']');
1152                                         parse.skip_spaces(true);
1153                                         cerr << "Ignoring multirow's vpos arg '"
1154                                              << vpos << "'!" << endl;
1155                                 }
1156                                 // how many cells?
1157                                 parse.get_token();
1158                                 size_t const ncells =
1159                                         convert<unsigned int>(parse.verbatim_item());
1160                                 // We do not support the bigstrut arg yet.
1161                                 if (parse.hasOpt()) {
1162                                         string const bs = parse.getArg('[', ']');
1163                                         parse.skip_spaces(true);
1164                                         cerr << "Ignoring multirow's bigstrut arg '"
1165                                              << bs << "'!" << endl;
1166                                 }
1167                                 // the width argument
1168                                 string const width = parse.getArg('{', '}');
1169                                 // the vmove arg
1170                                 string vmove;
1171                                 if (parse.hasOpt()) {
1172                                         vmove = parse.getArg('[', ']');
1173                                         parse.skip_spaces(true);
1174                                 }
1175
1176                                 if (width != "*")
1177                                         colinfo[col].width = width;
1178                                 if (!vmove.empty())
1179                                         cellinfo[row][col].mroffset = vmove;
1180                                 cellinfo[row][col].multi = CELL_BEGIN_OF_MULTIROW;
1181                                 cellinfo[row][col].leftlines  = colinfo[col].leftlines;
1182                                 cellinfo[row][col].rightlines = colinfo[col].rightlines;
1183                                 cellinfo[row][col].mrxnum = ncells - 1;
1184
1185                                 ostringstream os2;
1186                                 parse_text_in_inset(parse, os2, FLAG_ITEM, false, context);
1187                                 if (!cellinfo[row][col].content.empty()) {
1188                                         // This may or may not work in LaTeX,
1189                                         // but it does not work in LyX.
1190                                         // FIXME: Handle it correctly!
1191                                         cerr << "Moving cell content '"
1192                                              << cells[cell]
1193                                              << "' into a multirow cell. "
1194                                                 "This will probably not work."
1195                                              << endl;
1196                                 }
1197                                 cellinfo[row][col].content += os2.str();
1198                         } else if (parse.next_token().cs() == "multicolumn") {
1199                                 // how many cells?
1200                                 parse.get_token();
1201                                 size_t const ncells =
1202                                         convert<unsigned int>(parse.verbatim_item());
1203
1204                                 // special cell properties alignment
1205                                 vector<ColInfo> t;
1206                                 handle_colalign(parse, t, ColInfo());
1207                                 parse.skip_spaces(true);
1208                                 ColInfo & ci = t.front();
1209
1210                                 // The logic of LyX for multicolumn vertical
1211                                 // lines is too complicated to reproduce it
1212                                 // here (see LyXTabular::TeXCellPreamble()).
1213                                 // Therefore we simply put everything in the
1214                                 // special field.
1215                                 ci2special(ci);
1216
1217                                 cellinfo[row][col].multi      = CELL_BEGIN_OF_MULTICOLUMN;
1218                                 cellinfo[row][col].align      = ci.align;
1219                                 cellinfo[row][col].special    = ci.special;
1220                                 cellinfo[row][col].leftlines  = ci.leftlines;
1221                                 cellinfo[row][col].rightlines = ci.rightlines;
1222                                 ostringstream os2;
1223                                 parse_text_in_inset(parse, os2, FLAG_ITEM, false, context);
1224                                 if (!cellinfo[row][col].content.empty()) {
1225                                         // This may or may not work in LaTeX,
1226                                         // but it does not work in LyX.
1227                                         // FIXME: Handle it correctly!
1228                                         cerr << "Moving cell content '"
1229                                              << cells[cell]
1230                                              << "' into a multicolumn cell. "
1231                                                 "This will probably not work."
1232                                              << endl;
1233                                 }
1234                                 cellinfo[row][col].content += os2.str();
1235
1236                                 // add dummy cells for multicol
1237                                 for (size_t i = 0; i < ncells - 1; ++i) {
1238                                         ++col;
1239                                         if (col >= colinfo.size()) {
1240                                                 cerr << "The cell '"
1241                                                         << cells[cell]
1242                                                         << "' specifies "
1243                                                         << convert<string>(ncells)
1244                                                         << " columns while the table has only "
1245                                                         << convert<string>(colinfo.size())
1246                                                         << " columns!"
1247                                                         << " Therefore the surplus columns will be ignored."
1248                                                         << endl;
1249                                                 break;
1250                                         }
1251                                         cellinfo[row][col].multi = CELL_PART_OF_MULTICOLUMN;
1252                                         cellinfo[row][col].align = 'c';
1253                                 }
1254
1255                         } else if (col == 0 && colinfo.size() > 1 &&
1256                                    is_long_tabular &&
1257                                    parse.next_token().cs() == "caption") {
1258                                 // longtable caption support in LyX is a hack:
1259                                 // Captions require a row of their own with
1260                                 // the caption flag set to true, having only
1261                                 // one multicolumn cell. The contents of that
1262                                 // cell must contain exactly one caption inset
1263                                 // and nothing else.
1264                                 // Fortunately, the caption flag is only needed
1265                                 // for tables with more than one column.
1266                                 rowinfo[row].caption = true;
1267                                 for (size_t c = 1; c < cells.size(); ++c) {
1268                                         if (!cells[c].empty()) {
1269                                                 cerr << "Moving cell content '"
1270                                                      << cells[c]
1271                                                      << "' into the caption cell. "
1272                                                         "This will probably not work."
1273                                                      << endl;
1274                                                 cells[0] += cells[c];
1275                                         }
1276                                 }
1277                                 cells.resize(1);
1278                                 cellinfo[row][col].align      = colinfo[col].align;
1279                                 cellinfo[row][col].multi      = CELL_BEGIN_OF_MULTICOLUMN;
1280                                 ostringstream os2;
1281                                 parse_text_in_inset(parse, os2, FLAG_CELL, false, context);
1282                                 cellinfo[row][col].content += os2.str();
1283                                 // add dummy multicolumn cells
1284                                 for (size_t c = 1; c < colinfo.size(); ++c)
1285                                         cellinfo[row][c].multi = CELL_PART_OF_MULTICOLUMN;
1286                         } else {
1287                                 bool turn = false;
1288                                 int rotate = 0;
1289                                 if (parse.next_token().cs() == "begin") {
1290                                         parse.pushPosition();
1291                                         parse.get_token();
1292                                         string const env = parse.getArg('{', '}');
1293                                         if (env == "sideways" || env == "turn") {
1294                                                 string angle = "90";
1295                                                 if (env == "turn") {
1296                                                         turn = true;
1297                                                         angle = parse.getArg('{', '}');
1298                                                 }
1299                                                 active_environments.push_back(env);
1300                                                 parse.ertEnvironment(env);
1301                                                 active_environments.pop_back();
1302                                                 parse.skip_spaces();
1303                                                 if (!parse.good() && support::isStrInt(angle))
1304                                                         rotate = convert<int>(angle);
1305                                         }
1306                                         parse.popPosition();
1307                                 }
1308                                 cellinfo[row][col].leftlines  = colinfo[col].leftlines;
1309                                 cellinfo[row][col].rightlines = colinfo[col].rightlines;
1310                                 cellinfo[row][col].align      = colinfo[col].align;
1311                                 ostringstream os2;
1312                                 if (rotate != 0) {
1313                                         cellinfo[row][col].rotate = rotate;
1314                                         parse.get_token();
1315                                         active_environments.push_back(parse.getArg('{', '}'));
1316                                         if (turn)
1317                                                 parse.getArg('{', '}');
1318                                         parse_text_in_inset(parse, os2, FLAG_END, false, context);
1319                                         active_environments.pop_back();
1320                                         preamble.registerAutomaticallyLoadedPackage("rotating");
1321                                 } else {
1322                                         parse_text_in_inset(parse, os2, FLAG_CELL, false, context);
1323                                 }
1324                                 cellinfo[row][col].content += os2.str();
1325                         }
1326                 }
1327
1328                 //cerr << "//  handle almost empty last row what we have\n";
1329                 // handle almost empty last row
1330                 if (row && lines[row].empty() && row + 1 == rowinfo.size()) {
1331                         //cerr << "remove empty last line\n";
1332                         if (rowinfo[row].topline)
1333                                 rowinfo[row - 1].bottomline = true;
1334                         for (size_t col = 0; col < colinfo.size(); ++col)
1335                                 if (cellinfo[row][col].topline)
1336                                         cellinfo[row - 1][col].bottomline = true;
1337                         rowinfo.pop_back();
1338                 }
1339
1340                 ++row;
1341         }
1342
1343         // Now we have the table structure and content in rowinfo, colinfo
1344         // and cellinfo.
1345         // Unfortunately LyX has some limitations that we need to work around.
1346
1347         // Some post work
1348         for (size_t row = 0; row < rowinfo.size(); ++row) {
1349                 for (size_t col = 0; col < cellinfo[row].size(); ++col) {
1350                         // Convert cells with special content to multicolumn cells
1351                         // (LyX ignores the special field for non-multicolumn cells).
1352                         if (cellinfo[row][col].multi == CELL_NORMAL &&
1353                             !cellinfo[row][col].special.empty())
1354                                 cellinfo[row][col].multi = CELL_BEGIN_OF_MULTICOLUMN;
1355                         // Add multirow dummy cells
1356                         if (row > 1 && (cellinfo[row - 1][col].multi == CELL_PART_OF_MULTIROW
1357                                         || cellinfo[row - 1][col].multi == CELL_BEGIN_OF_MULTIROW)
1358                                     && cellinfo[row - 1][col].mrxnum > 0) {
1359                                 // add dummy cells for multirow
1360                                 cellinfo[row][col].multi = CELL_PART_OF_MULTIROW;
1361                                 cellinfo[row][col].align = 'c';
1362                                 cellinfo[row][col].mrxnum = cellinfo[row - 1][col].mrxnum - 1;
1363                         }
1364                 }
1365         }
1366
1367         // Distribute lines from rows/columns to cells
1368         // The code was stolen from convert_tablines() in lyx2lyx/lyx_1_6.py.
1369         // Each standard cell inherits the settings of the corresponding
1370         // rowinfo/colinfo. This works because all cells with individual
1371         // settings were converted to multicolumn cells above.
1372         // Each multicolumn cell inherits the settings of the rowinfo/colinfo
1373         // corresponding to the first column of the multicolumn cell (default
1374         // of the multicol package). This works because the special field
1375         // overrides the line fields.
1376         for (size_t row = 0; row < rowinfo.size(); ++row) {
1377                 for (size_t col = 0; col < cellinfo[row].size(); ++col) {
1378                         if (cellinfo[row][col].multi == CELL_NORMAL) {
1379                                 cellinfo[row][col].topline = rowinfo[row].topline;
1380                                 cellinfo[row][col].bottomline = rowinfo[row].bottomline;
1381                                 cellinfo[row][col].leftlines = colinfo[col].leftlines;
1382                                 cellinfo[row][col].rightlines = colinfo[col].rightlines;
1383                         } else if (cellinfo[row][col].multi == CELL_BEGIN_OF_MULTICOLUMN) {
1384                                 size_t s = col + 1;
1385                                 while (s < cellinfo[row].size() &&
1386                                        cellinfo[row][s].multi == CELL_PART_OF_MULTICOLUMN)
1387                                         s++;
1388                                 if (s < cellinfo[row].size() &&
1389                                     cellinfo[row][s].multi != CELL_BEGIN_OF_MULTICOLUMN)
1390                                         cellinfo[row][col].rightlines = colinfo[col].rightlines;
1391                                 if (col > 0 && cellinfo[row][col-1].multi == CELL_NORMAL)
1392                                         cellinfo[row][col].leftlines = colinfo[col].leftlines;
1393                         } else if (cellinfo[row][col].multi == CELL_BEGIN_OF_MULTIROW) {
1394                                 size_t s = row + 1;
1395                                 while (s < rowinfo.size() &&
1396                                        cellinfo[s][col].multi == CELL_PART_OF_MULTIROW)
1397                                         s++;
1398                                 if (s < cellinfo[row].size() &&
1399                                     cellinfo[s][col].multi != CELL_BEGIN_OF_MULTIROW)
1400                                         cellinfo[row][col].bottomline = rowinfo[row].bottomline;
1401                                 if (row > 0 && cellinfo[row - 1][col].multi == CELL_NORMAL)
1402                                         cellinfo[row][col].topline = rowinfo[row].topline;
1403                         }
1404                 }
1405         }
1406
1407         if (booktabs)
1408                 preamble.registerAutomaticallyLoadedPackage("booktabs");
1409         if (name == "longtable")
1410                 preamble.registerAutomaticallyLoadedPackage("longtable");
1411         else if (name == "xltabular")
1412                 preamble.registerAutomaticallyLoadedPackage("xltabular");
1413         else if (name == "tabularx")
1414                 preamble.registerAutomaticallyLoadedPackage("tabularx");
1415
1416         //cerr << "// output what we have\n";
1417         // output what we have
1418         string const rotate = "0";
1419         os << "\n<lyxtabular version=\"3\" rows=\"" << rowinfo.size()
1420            << "\" columns=\"" << colinfo.size() << "\">\n";
1421         os << "<features"
1422            << write_attribute("rotate", rotate)
1423            << write_attribute("booktabs", booktabs)
1424            << write_attribute("islongtable", is_long_tabular);
1425         if (is_long_tabular) {
1426                 os << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1427                    << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1428                    << write_attribute("firstHeadEmpty", endfirsthead.empty)
1429                    << write_attribute("headTopDL", endhead.topDL)
1430                    << write_attribute("headBottomDL", endhead.bottomDL)
1431                    << write_attribute("footTopDL", endfoot.topDL)
1432                    << write_attribute("footBottomDL", endfoot.bottomDL)
1433                    << write_attribute("lastFootTopDL", endlastfoot.topDL)
1434                    << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1435                    << write_attribute("lastFootEmpty", endlastfoot.empty);
1436                 if (!halign.empty())
1437                         os << write_attribute("longtabularalignment", halign);
1438         } else
1439                 os << write_attribute("tabularvalignment", tabularvalignment);
1440                    
1441         os << write_attribute("tabularwidth", tabularwidth) << ">\n";
1442
1443         //cerr << "// after header\n";
1444         for (size_t col = 0; col < colinfo.size(); ++col) {
1445                 os << "<column alignment=\""
1446                    << verbose_align(colinfo[col].align) << "\""
1447                    << " valignment=\""
1448                    << verbose_valign(colinfo[col].valign) << "\""
1449                    << write_attribute("width", translate_len(colinfo[col].width))
1450                    << write_attribute("special", colinfo[col].special)
1451                    << write_attribute("varwidth", colinfo[col].varwidth)
1452                    << ">\n";
1453         }
1454         //cerr << "// after cols\n";
1455
1456         for (size_t row = 0; row < rowinfo.size(); ++row) {
1457                 os << "<row"
1458                    << write_attribute("topspace", rowinfo[row].top_space)
1459                    << write_attribute("bottomspace", rowinfo[row].bottom_space)
1460                    << write_attribute("interlinespace", rowinfo[row].interline_space)
1461                    << write_attribute("endhead",
1462                                       rowinfo[row].type == LT_HEAD)
1463                    << write_attribute("endfirsthead",
1464                                       rowinfo[row].type == LT_FIRSTHEAD)
1465                    << write_attribute("endfoot",
1466                                       rowinfo[row].type == LT_FOOT)
1467                    << write_attribute("endlastfoot",
1468                                       rowinfo[row].type == LT_LASTFOOT)
1469                    << write_attribute("newpage", rowinfo[row].newpage)
1470                    << write_attribute("caption", rowinfo[row].caption)
1471                    << ">\n";
1472                 for (size_t col = 0; col < colinfo.size(); ++col) {
1473                         CellInfo const & cell = cellinfo[row][col];
1474                         os << "<cell";
1475                         if (cell.multi == CELL_BEGIN_OF_MULTICOLUMN
1476                             || cell.multi == CELL_PART_OF_MULTICOLUMN)
1477                                 os << " multicolumn=\"" << cell.multi << "\"";
1478                         if (cell.multi == CELL_BEGIN_OF_MULTIROW
1479                             || cell.multi == CELL_PART_OF_MULTIROW)
1480                                 os << " multirow=\"" << cell.multi << "\"";
1481                         os << " alignment=\"" << verbose_align(cell.align)
1482                            << "\""
1483                            << " valignment=\"" << verbose_valign(cell.valign)
1484                            << "\""
1485                            << write_attribute("topline", cell.topline)
1486                            << write_attribute("bottomline", cell.bottomline)
1487                            << write_attribute("leftline", cell.leftlines > 0)
1488                            << write_attribute("rightline", cell.rightlines > 0)
1489                            << write_attribute("rotate", cell.rotate)
1490                            << write_attribute("mroffset", cell.mroffset);
1491                         //cerr << "\nrow: " << row << " col: " << col;
1492                         //if (cell.topline)
1493                         //      cerr << " topline=\"true\"";
1494                         //if (cell.bottomline)
1495                         //      cerr << " bottomline=\"true\"";
1496                         os << " usebox=\"none\""
1497                            << write_attribute("width", translate_len(cell.width));
1498                         if (cell.multi != CELL_NORMAL)
1499                                 os << write_attribute("special", cell.special);
1500                         os << ">"
1501                            << "\n\\begin_inset Text\n"
1502                            << cell.content
1503                            << "\n\\end_inset\n"
1504                            << "</cell>\n";
1505                 }
1506                 os << "</row>\n";
1507         }
1508
1509         os << "</lyxtabular>\n";
1510 }
1511
1512
1513
1514
1515 // }])
1516
1517
1518 } // namespace lyx