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