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