]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/table.cpp
More requires --> required, for C++2a.
[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 wether 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 (size_t col = 0; col < colinfo.size(); ++col)
593                 fix_colalign(colinfo[col]);
594 }
595
596
597 /*!
598  * Parse hlines and similar stuff.
599  * \returns wether 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 wether 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 (size_t col = 0; col < ci.size(); ++col)
925                 ci[col].topline = true;
926 }
927
928
929 void handle_hline_below(RowInfo & ri, vector<CellInfo> & ci)
930 {
931         ri.bottomline = true;
932         for (size_t col = 0; col < ci.size(); ++col)
933                 ci[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 & context)
943 {
944         bool const is_long_tabular(name == "longtable" || name == "xltabular");
945         bool booktabs = false;
946         string tabularvalignment("middle");
947         string posopts = p.getOpt();
948         if (!posopts.empty()) {
949                 if (posopts == "[t]")
950                         tabularvalignment = "top";
951                 else if (posopts == "[b]")
952                         tabularvalignment = "bottom";
953                 else
954                         cerr << "vertical tabular positioning '"
955                              << posopts << "' ignored\n";
956         }
957
958         vector<ColInfo> colinfo;
959
960         // handle column formatting
961         handle_colalign(p, colinfo, ColInfo());
962         fix_colalign(colinfo);
963
964         // first scan of cells
965         // use table mode to keep it minimal-invasive
966         // not exactly what's TeX doing...
967         vector<string> lines;
968         ostringstream ss;
969         RowPosition rowpos = ROW_START;
970         parse_table(p, ss, is_long_tabular, rowpos, FLAG_END);
971         split(ss.str(), lines, LINE);
972
973         vector< vector<CellInfo> > cellinfo(lines.size());
974         vector<RowInfo> rowinfo(lines.size());
975         ltType endfirsthead;
976         ltType endhead;
977         ltType endfoot;
978         ltType endlastfoot;
979
980         // split into rows
981         //cerr << "// split into rows\n";
982         for (size_t row = 0; row < rowinfo.size();) {
983
984                 // init row
985                 cellinfo[row].resize(colinfo.size());
986                 bool deletelastrow = false;
987
988                 // split row
989                 vector<string> dummy;
990                 //cerr << "\n########### LINE: " << lines[row] << "########\n";
991                 split(lines[row], dummy, HLINE);
992
993                 // handle horizontal line fragments
994                 // we do only expect this for a last line without '\\'
995                 if (dummy.size() != 3) {
996                         if ((dummy.size() != 1 && dummy.size() != 2) ||
997                             row != rowinfo.size() - 1)
998                                 cerr << "unexpected dummy size: " << dummy.size()
999                                         << " content: " << lines[row] << "\n";
1000                         dummy.resize(3);
1001                 }
1002                 lines[row] = dummy[1];
1003
1004                 //cerr << "line: " << row << " above 0: " << dummy[0] << "\n";
1005                 //cerr << "line: " << row << " below 2: " << dummy[2] <<  "\n";
1006                 //cerr << "line: " << row << " cells 1: " << dummy[1] <<  "\n";
1007
1008                 for (int i = 0; i <= 2; i += 2) {
1009                         //cerr << "   reading from line string '" << dummy[i] << "'\n";
1010                         Parser p1(dummy[size_type(i)]);
1011                         while (p1.good()) {
1012                                 Token t = p1.get_token();
1013                                 //cerr << "read token: " << t << "\n";
1014                                 if (t.cs() == "hline" || t.cs() == "toprule" ||
1015                                     t.cs() == "midrule" ||
1016                                     t.cs() == "bottomrule") {
1017                                         if (t.cs() != "hline")
1018                                                 booktabs = true;
1019                                         if (i == 0) {
1020                                                 if (rowinfo[row].topline) {
1021                                                         if (row > 0) // extra bottomline above
1022                                                                 handle_hline_below(rowinfo[row - 1], cellinfo[row - 1]);
1023                                                         else
1024                                                                 cerr << "dropping extra "
1025                                                                      << t.cs() << '\n';
1026                                                         //cerr << "below row: " << row-1 << endl;
1027                                                 } else {
1028                                                         handle_hline_above(rowinfo[row], cellinfo[row]);
1029                                                         //cerr << "above row: " << row << endl;
1030                                                 }
1031                                         } else {
1032                                                 //cerr << "below row: " << row << endl;
1033                                                 handle_hline_below(rowinfo[row], cellinfo[row]);
1034                                         }
1035                                 } else if (t.cs() == "cline" || t.cs() == "cmidrule") {
1036                                         string trim;
1037                                         if (t.cs() == "cmidrule") {
1038                                                 booktabs = true;
1039                                                 trim = p1.getFullParentheseArg();
1040                                         }
1041                                         string arg = p1.verbatim_item();
1042                                         //cerr << "read " << t.cs() << " arg: '" << arg << "', trim: '" << trim << "'\n";
1043                                         vector<string> cols;
1044                                         split(arg, cols, '-');
1045                                         cols.resize(2);
1046                                         size_t from = convert<unsigned int>(cols[0]);
1047                                         if (from == 0)
1048                                                 cerr << "Could not parse "
1049                                                      << t.cs() << " start column."
1050                                                      << endl;
1051                                         else
1052                                                 // 1 based index -> 0 based
1053                                                 --from;
1054                                         if (from >= colinfo.size()) {
1055                                                 cerr << t.cs() << " starts at "
1056                                                         "non existing column "
1057                                                      << (from + 1) << endl;
1058                                                 from = colinfo.size() - 1;
1059                                         }
1060                                         size_t to = convert<unsigned int>(cols[1]);
1061                                         if (to == 0)
1062                                                 cerr << "Could not parse "
1063                                                      << t.cs() << " end column."
1064                                                      << endl;
1065                                         else
1066                                                 // 1 based index -> 0 based
1067                                                 --to;
1068                                         if (to >= colinfo.size()) {
1069                                                 cerr << t.cs() << " ends at "
1070                                                         "non existing column "
1071                                                      << (to + 1) << endl;
1072                                                 to = colinfo.size() - 1;
1073                                         }
1074                                         for (size_t col = from; col <= to; ++col) {
1075                                                 //cerr << "row: " << row << " col: " << col << " i: " << i << endl;
1076                                                 if (i == 0) {
1077                                                         rowinfo[row].topline = true;
1078                                                         cellinfo[row][col].topline = true;
1079                                                         if (support::contains(trim, 'l') && col == from) {
1080                                                                 //rowinfo[row].topline_ltrim = true;
1081                                                                 cellinfo[row][col].topline_ltrim = true;
1082                                                         }
1083                                                         else if (support::contains(trim, 'r') && col == to) {
1084                                                                 //rowinfo[row].topline_rtrim = true;
1085                                                                 cellinfo[row][col].topline_rtrim = true;
1086                                                         }
1087                                                 } else {
1088                                                         rowinfo[row].bottomline = true;
1089                                                         cellinfo[row][col].bottomline = true;
1090                                                         if (support::contains(trim, 'l') && col == from) {
1091                                                                 //rowinfo[row].bottomline_ltrim = true;
1092                                                                 cellinfo[row][col].bottomline_ltrim = true;
1093                                                         }
1094                                                         else if (support::contains(trim, 'r') && col == to) {
1095                                                                 //rowinfo[row].bottomline_rtrim = true;
1096                                                                 cellinfo[row][col].bottomline_rtrim = true;
1097                                                         }
1098                                                 }
1099                                         }
1100                                 } else if (t.cs() == "addlinespace") {
1101                                         booktabs = true;
1102                                         string const opt = p.next_token().cat() == catBegin ?
1103                                                         p.verbatim_item() : string();
1104                                         if (i == 0) {
1105                                                 if (opt.empty())
1106                                                         rowinfo[row].top_space = "default";
1107                                                 else
1108                                                         rowinfo[row].top_space = translate_len(opt);
1109                                         } else if (rowinfo[row].bottomline) {
1110                                                 if (opt.empty())
1111                                                         rowinfo[row].bottom_space = "default";
1112                                                 else
1113                                                         rowinfo[row].bottom_space = translate_len(opt);
1114                                         } else {
1115                                                 if (opt.empty())
1116                                                         rowinfo[row].interline_space = "default";
1117                                                 else
1118                                                         rowinfo[row].interline_space = translate_len(opt);
1119                                         }
1120                                 } else if (t.cs() == "endhead") {
1121                                         if (i == 0)
1122                                                 endhead.empty = true;
1123                                         else
1124                                                 rowinfo[row].type = LT_HEAD;
1125                                         for (int r = row - 1; r >= 0; --r) {
1126                                                 if (rowinfo[r].type != LT_NORMAL)
1127                                                         break;
1128                                                 rowinfo[r].type = LT_HEAD;
1129                                                 endhead.empty = false;
1130                                         }
1131                                         endhead.set = true;
1132                                 } else if (t.cs() == "endfirsthead") {
1133                                         if (i == 0)
1134                                                 endfirsthead.empty = true;
1135                                         else
1136                                                 rowinfo[row].type = LT_FIRSTHEAD;
1137                                         for (int r = row - 1; r >= 0; --r) {
1138                                                 if (rowinfo[r].type != LT_NORMAL)
1139                                                         break;
1140                                                 rowinfo[r].type = LT_FIRSTHEAD;
1141                                                 endfirsthead.empty = false;
1142                                         }
1143                                         endfirsthead.set = true;
1144                                 } else if (t.cs() == "endfoot") {
1145                                         if (i == 0)
1146                                                 endfoot.empty = true;
1147                                         else
1148                                                 rowinfo[row].type = LT_FOOT;
1149                                         for (int r = row - 1; r >= 0; --r) {
1150                                                 if (rowinfo[r].type != LT_NORMAL)
1151                                                         break;
1152                                                 rowinfo[r].type = LT_FOOT;
1153                                                 endfoot.empty = false;
1154                                         }
1155                                         endfoot.set = true;
1156                                 } else if (t.cs() == "endlastfoot") {
1157                                         if (i == 0)
1158                                                 endlastfoot.empty = true;
1159                                         else
1160                                                 rowinfo[row].type = LT_LASTFOOT;
1161                                         for (int r = row - 1; r >= 0; --r) {
1162                                                 if (rowinfo[r].type != LT_NORMAL)
1163                                                         break;
1164                                                 rowinfo[r].type = LT_LASTFOOT;
1165                                                 endlastfoot.empty = false;
1166                                         }
1167                                         endlastfoot.set = true;
1168                                 } else if (t.cs() == "newpage") {
1169                                         if (i == 0) {
1170                                                 if (row > 0)
1171                                                         rowinfo[row - 1].newpage = true;
1172                                                 else
1173                                                         // This does not work in LaTeX
1174                                                         cerr << "Ignoring "
1175                                                                 "'\\newpage' "
1176                                                                 "before rows."
1177                                                              << endl;
1178                                         } else
1179                                                 rowinfo[row].newpage = true;
1180                                 } else {
1181                                         cerr << "unexpected line token: " << t << endl;
1182                                 }
1183                         }
1184                 }
1185
1186                 // LyX ends headers and footers always with \tabularnewline.
1187                 // This causes one additional row in the output.
1188                 // If the last row of a header/footer is empty, we can work
1189                 // around that by removing it.
1190                 if (row > 1) {
1191                         RowInfo test = rowinfo[row-1];
1192                         test.type = LT_NORMAL;
1193                         if (lines[row-1].empty() && !test.special()) {
1194                                 switch (rowinfo[row-1].type) {
1195                                 case LT_FIRSTHEAD:
1196                                         if (rowinfo[row].type != LT_FIRSTHEAD &&
1197                                             rowinfo[row-2].type == LT_FIRSTHEAD)
1198                                                 deletelastrow = true;
1199                                         break;
1200                                 case LT_HEAD:
1201                                         if (rowinfo[row].type != LT_HEAD &&
1202                                             rowinfo[row-2].type == LT_HEAD)
1203                                                 deletelastrow = true;
1204                                         break;
1205                                 case LT_FOOT:
1206                                         if (rowinfo[row].type != LT_FOOT &&
1207                                             rowinfo[row-2].type == LT_FOOT)
1208                                                 deletelastrow = true;
1209                                         break;
1210                                 case LT_LASTFOOT:
1211                                         if (rowinfo[row].type != LT_LASTFOOT &&
1212                                             rowinfo[row-2].type == LT_LASTFOOT)
1213                                                 deletelastrow = true;
1214                                         break;
1215                                 case LT_NORMAL:
1216                                         break;
1217                                 }
1218                         }
1219                 }
1220
1221                 if (deletelastrow) {
1222                         lines.erase(lines.begin() + (row - 1));
1223                         rowinfo.erase(rowinfo.begin() + (row - 1));
1224                         cellinfo.erase(cellinfo.begin() + (row - 1));
1225                         continue;
1226                 }
1227
1228                 // split into cells
1229                 vector<string> cells;
1230                 split(lines[row], cells, TAB);
1231                 for (size_t col = 0, cell = 0; cell < cells.size();
1232                      ++col, ++cell) {
1233                         //cerr << "cell content: '" << cells[cell] << "'\n";
1234                         if (col >= colinfo.size()) {
1235                                 // This does not work in LaTeX
1236                                 cerr << "Ignoring extra cell '"
1237                                      << cells[cell] << "'." << endl;
1238                                 continue;
1239                         }
1240                         string cellcont = cells[cell];
1241                         // For decimal cells, ass the content of the second one to the first one
1242                         // of a pair.
1243                         if (colinfo[col].decimal_point != '\0' && colinfo[col].align == 'd' && cell < cells.size() - 1)
1244                                 cellcont += colinfo[col].decimal_point + cells[cell + 1];
1245                         Parser parse(cellcont);
1246                         parse.skip_spaces();
1247                         //cells[cell] << "'\n";
1248                         if (parse.next_token().cs() == "multirow") {
1249                                 // We do not support the vpos arg yet.
1250                                 if (parse.hasOpt()) {
1251                                         string const vpos = parse.getArg('[', ']');
1252                                         parse.skip_spaces(true);
1253                                         cerr << "Ignoring multirow's vpos arg '"
1254                                              << vpos << "'!" << endl;
1255                                 }
1256                                 // how many cells?
1257                                 parse.get_token();
1258                                 size_t const ncells =
1259                                         convert<unsigned int>(parse.verbatim_item());
1260                                 // We do not support the bigstrut arg yet.
1261                                 if (parse.hasOpt()) {
1262                                         string const bs = parse.getArg('[', ']');
1263                                         parse.skip_spaces(true);
1264                                         cerr << "Ignoring multirow's bigstrut arg '"
1265                                              << bs << "'!" << endl;
1266                                 }
1267                                 // the width argument
1268                                 string const width = parse.getArg('{', '}');
1269                                 // the vmove arg
1270                                 string vmove;
1271                                 if (parse.hasOpt()) {
1272                                         vmove = parse.getArg('[', ']');
1273                                         parse.skip_spaces(true);
1274                                 }
1275
1276                                 if (width != "*")
1277                                         colinfo[col].width = width;
1278                                 if (!vmove.empty())
1279                                         cellinfo[row][col].mroffset = vmove;
1280                                 cellinfo[row][col].multi = CELL_BEGIN_OF_MULTIROW;
1281                                 cellinfo[row][col].leftlines  = colinfo[col].leftlines;
1282                                 cellinfo[row][col].rightlines = colinfo[col].rightlines;
1283                                 cellinfo[row][col].mrxnum = ncells - 1;
1284
1285                                 ostringstream os2;
1286                                 parse_text_in_inset(parse, os2, FLAG_ITEM, false, context);
1287                                 if (!cellinfo[row][col].content.empty()) {
1288                                         // This may or may not work in LaTeX,
1289                                         // but it does not work in LyX.
1290                                         // FIXME: Handle it correctly!
1291                                         cerr << "Moving cell content '"
1292                                              << cells[cell]
1293                                              << "' into a multirow cell. "
1294                                                 "This will probably not work."
1295                                              << endl;
1296                                 }
1297                                 cellinfo[row][col].content += os2.str();
1298                         } else if (parse.next_token().cs() == "multicolumn") {
1299                                 // how many cells?
1300                                 parse.get_token();
1301                                 size_t const ncells =
1302                                         convert<unsigned int>(parse.verbatim_item());
1303
1304                                 // special cell properties alignment
1305                                 vector<ColInfo> t;
1306                                 handle_colalign(parse, t, ColInfo());
1307                                 parse.skip_spaces(true);
1308                                 ColInfo & ci = t.front();
1309
1310                                 // The logic of LyX for multicolumn vertical
1311                                 // lines is too complicated to reproduce it
1312                                 // here (see LyXTabular::TeXCellPreamble()).
1313                                 // Therefore we simply put everything in the
1314                                 // special field.
1315                                 ci2special(ci);
1316
1317                                 cellinfo[row][col].multi      = CELL_BEGIN_OF_MULTICOLUMN;
1318                                 cellinfo[row][col].align      = ci.align;
1319                                 cellinfo[row][col].special    = ci.special;
1320                                 cellinfo[row][col].leftlines  = ci.leftlines;
1321                                 cellinfo[row][col].rightlines = ci.rightlines;
1322                                 ostringstream os2;
1323                                 parse_text_in_inset(parse, os2, FLAG_ITEM, false, context);
1324                                 if (!cellinfo[row][col].content.empty()) {
1325                                         // This may or may not work in LaTeX,
1326                                         // but it does not work in LyX.
1327                                         // FIXME: Handle it correctly!
1328                                         cerr << "Moving cell content '"
1329                                              << cells[cell]
1330                                              << "' into a multicolumn cell. "
1331                                                 "This will probably not work."
1332                                              << endl;
1333                                 }
1334                                 cellinfo[row][col].content += os2.str();
1335
1336                                 // add dummy cells for multicol
1337                                 for (size_t i = 0; i < ncells - 1; ++i) {
1338                                         ++col;
1339                                         if (col >= colinfo.size()) {
1340                                                 cerr << "The cell '"
1341                                                         << cells[cell]
1342                                                         << "' specifies "
1343                                                         << convert<string>(ncells)
1344                                                         << " columns while the table has only "
1345                                                         << convert<string>(colinfo.size())
1346                                                         << " columns!"
1347                                                         << " Therefore the surplus columns will be ignored."
1348                                                         << endl;
1349                                                 break;
1350                                         }
1351                                         cellinfo[row][col].multi = CELL_PART_OF_MULTICOLUMN;
1352                                         cellinfo[row][col].align = 'c';
1353                                 }
1354
1355                         } else if (col == 0 && colinfo.size() > 1 &&
1356                                    is_long_tabular &&
1357                                    parse.next_token().cs() == "caption") {
1358                                 // longtable caption support in LyX is a hack:
1359                                 // Captions require a row of their own with
1360                                 // the caption flag set to true, having only
1361                                 // one multicolumn cell. The contents of that
1362                                 // cell must contain exactly one caption inset
1363                                 // and nothing else.
1364                                 // Fortunately, the caption flag is only needed
1365                                 // for tables with more than one column.
1366                                 rowinfo[row].caption = true;
1367                                 for (size_t c = 1; c < cells.size(); ++c) {
1368                                         if (!cells[c].empty()) {
1369                                                 cerr << "Moving cell content '"
1370                                                      << cells[c]
1371                                                      << "' into the caption cell. "
1372                                                         "This will probably not work."
1373                                                      << endl;
1374                                                 cells[0] += cells[c];
1375                                         }
1376                                 }
1377                                 cells.resize(1);
1378                                 cellinfo[row][col].align      = colinfo[col].align;
1379                                 cellinfo[row][col].multi      = CELL_BEGIN_OF_MULTICOLUMN;
1380                                 ostringstream os2;
1381                                 parse_text_in_inset(parse, os2, FLAG_CELL, false, context);
1382                                 cellinfo[row][col].content += os2.str();
1383                                 // add dummy multicolumn cells
1384                                 for (size_t c = 1; c < colinfo.size(); ++c)
1385                                         cellinfo[row][c].multi = CELL_PART_OF_MULTICOLUMN;
1386                         } else {
1387                                 bool turn = false;
1388                                 int rotate = 0;
1389                                 if (parse.next_token().cs() == "begin") {
1390                                         parse.pushPosition();
1391                                         parse.get_token();
1392                                         string const env = parse.getArg('{', '}');
1393                                         if (env == "sideways" || env == "turn") {
1394                                                 string angle = "90";
1395                                                 if (env == "turn") {
1396                                                         turn = true;
1397                                                         angle = parse.getArg('{', '}');
1398                                                 }
1399                                                 active_environments.push_back(env);
1400                                                 parse.ertEnvironment(env);
1401                                                 active_environments.pop_back();
1402                                                 parse.skip_spaces();
1403                                                 if (!parse.good() && support::isStrInt(angle))
1404                                                         rotate = convert<int>(angle);
1405                                         }
1406                                         parse.popPosition();
1407                                 }
1408                                 cellinfo[row][col].leftlines  = colinfo[col].leftlines;
1409                                 cellinfo[row][col].rightlines = colinfo[col].rightlines;
1410                                 cellinfo[row][col].align      = colinfo[col].align;
1411                                 ostringstream os2;
1412                                 if (rotate != 0) {
1413                                         cellinfo[row][col].rotate = rotate;
1414                                         parse.get_token();
1415                                         active_environments.push_back(parse.getArg('{', '}'));
1416                                         if (turn)
1417                                                 parse.getArg('{', '}');
1418                                         parse_text_in_inset(parse, os2, FLAG_END, false, context);
1419                                         active_environments.pop_back();
1420                                         preamble.registerAutomaticallyLoadedPackage("rotating");
1421                                 } else {
1422                                         parse_text_in_inset(parse, os2, FLAG_CELL, false, context);
1423                                 }
1424                                 cellinfo[row][col].content += os2.str();
1425                         }
1426                 }
1427
1428                 //cerr << "//  handle almost empty last row what we have\n";
1429                 // handle almost empty last row
1430                 if (row && lines[row].empty() && row + 1 == rowinfo.size()) {
1431                         //cerr << "remove empty last line\n";
1432                         if (rowinfo[row].topline)
1433                                 rowinfo[row - 1].bottomline = true;
1434                         for (size_t col = 0; col < colinfo.size(); ++col)
1435                                 if (cellinfo[row][col].topline)
1436                                         cellinfo[row - 1][col].bottomline = true;
1437                         rowinfo.pop_back();
1438                 }
1439
1440                 ++row;
1441         }
1442
1443         // Now we have the table structure and content in rowinfo, colinfo
1444         // and cellinfo.
1445         // Unfortunately LyX has some limitations that we need to work around.
1446
1447         // Some post work
1448         for (size_t row = 0; row < rowinfo.size(); ++row) {
1449                 for (size_t col = 0; col < cellinfo[row].size(); ++col) {
1450                         // Convert cells with special content to multicolumn cells
1451                         // (LyX ignores the special field for non-multicolumn cells).
1452                         if (cellinfo[row][col].multi == CELL_NORMAL &&
1453                             !cellinfo[row][col].special.empty())
1454                                 cellinfo[row][col].multi = CELL_BEGIN_OF_MULTICOLUMN;
1455                         // Add multirow dummy cells
1456                         if (row > 1 && (cellinfo[row - 1][col].multi == CELL_PART_OF_MULTIROW
1457                                         || cellinfo[row - 1][col].multi == CELL_BEGIN_OF_MULTIROW)
1458                                     && cellinfo[row - 1][col].mrxnum > 0) {
1459                                 // add dummy cells for multirow
1460                                 cellinfo[row][col].multi = CELL_PART_OF_MULTIROW;
1461                                 cellinfo[row][col].align = 'c';
1462                                 cellinfo[row][col].mrxnum = cellinfo[row - 1][col].mrxnum - 1;
1463                         }
1464                 }
1465         }
1466
1467         // Distribute lines from rows/columns to cells
1468         // The code was stolen from convert_tablines() in lyx2lyx/lyx_1_6.py.
1469         // Each standard cell inherits the settings of the corresponding
1470         // rowinfo/colinfo. This works because all cells with individual
1471         // settings were converted to multicolumn cells above.
1472         // Each multicolumn cell inherits the settings of the rowinfo/colinfo
1473         // corresponding to the first column of the multicolumn cell (default
1474         // of the multicol package). This works because the special field
1475         // overrides the line fields.
1476         for (size_t row = 0; row < rowinfo.size(); ++row) {
1477                 for (size_t col = 0; col < cellinfo[row].size(); ++col) {
1478                         if (cellinfo[row][col].multi == CELL_NORMAL) {
1479                                 cellinfo[row][col].topline = rowinfo[row].topline;
1480                                 cellinfo[row][col].bottomline = rowinfo[row].bottomline;
1481                                 cellinfo[row][col].leftlines = colinfo[col].leftlines;
1482                                 cellinfo[row][col].rightlines = colinfo[col].rightlines;
1483                         } else if (cellinfo[row][col].multi == CELL_BEGIN_OF_MULTICOLUMN) {
1484                                 size_t s = col + 1;
1485                                 while (s < cellinfo[row].size() &&
1486                                        cellinfo[row][s].multi == CELL_PART_OF_MULTICOLUMN)
1487                                         s++;
1488                                 if (s < cellinfo[row].size() &&
1489                                     cellinfo[row][s].multi != CELL_BEGIN_OF_MULTICOLUMN)
1490                                         cellinfo[row][col].rightlines = colinfo[col].rightlines;
1491                                 if (col > 0 && cellinfo[row][col-1].multi == CELL_NORMAL)
1492                                         cellinfo[row][col].leftlines = colinfo[col].leftlines;
1493                         } else if (cellinfo[row][col].multi == CELL_BEGIN_OF_MULTIROW) {
1494                                 size_t s = row + 1;
1495                                 while (s < rowinfo.size() &&
1496                                        cellinfo[s][col].multi == CELL_PART_OF_MULTIROW)
1497                                         s++;
1498                                 if (s < cellinfo[row].size() &&
1499                                     cellinfo[s][col].multi != CELL_BEGIN_OF_MULTIROW)
1500                                         cellinfo[row][col].bottomline = rowinfo[row].bottomline;
1501                                 if (row > 0 && cellinfo[row - 1][col].multi == CELL_NORMAL)
1502                                         cellinfo[row][col].topline = rowinfo[row].topline;
1503                         }
1504                 }
1505         }
1506
1507         if (booktabs)
1508                 preamble.registerAutomaticallyLoadedPackage("booktabs");
1509         if (name == "longtable")
1510                 preamble.registerAutomaticallyLoadedPackage("longtable");
1511         else if (name == "xltabular")
1512                 preamble.registerAutomaticallyLoadedPackage("xltabular");
1513         else if (name == "tabularx")
1514                 preamble.registerAutomaticallyLoadedPackage("tabularx");
1515
1516         //cerr << "// output what we have\n";
1517         // output what we have
1518         size_type cols = colinfo.size();
1519         for (size_t col = 0; col < colinfo.size(); ++col) {
1520                 if (colinfo[col].decimal_point != '\0' && colinfo[col].align != 'd')
1521                         --cols;
1522         }
1523         os << "\n<lyxtabular version=\"3\" rows=\"" << rowinfo.size()
1524            << "\" columns=\"" << cols << "\">\n";
1525         os << "<features"
1526            << write_attribute("rotate", context.tablerotation)
1527            << write_attribute("booktabs", booktabs)
1528            << write_attribute("islongtable", is_long_tabular);
1529         if (is_long_tabular) {
1530                 os << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1531                    << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1532                    << write_attribute("firstHeadEmpty", endfirsthead.empty)
1533                    << write_attribute("headTopDL", endhead.topDL)
1534                    << write_attribute("headBottomDL", endhead.bottomDL)
1535                    << write_attribute("footTopDL", endfoot.topDL)
1536                    << write_attribute("footBottomDL", endfoot.bottomDL)
1537                    << write_attribute("lastFootTopDL", endlastfoot.topDL)
1538                    << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1539                    << write_attribute("lastFootEmpty", endlastfoot.empty);
1540                 if (!halign.empty())
1541                         os << write_attribute("longtabularalignment", halign);
1542         } else
1543                 os << write_attribute("tabularvalignment", tabularvalignment);
1544                    
1545         os << write_attribute("tabularwidth", tabularwidth) << ">\n";
1546
1547         //cerr << "// after header\n";
1548         for (size_t col = 0; col < colinfo.size(); ++col) {
1549                 if (colinfo[col].decimal_point != '\0' && colinfo[col].align != 'd')
1550                         continue;
1551                 os << "<column alignment=\""
1552                            << verbose_align(colinfo[col].align) << "\"";
1553                 if (colinfo[col].decimal_point != '\0')
1554                         os << " decimal_point=\"" << colinfo[col].decimal_point << "\"";
1555                 os << " valignment=\""
1556                    << verbose_valign(colinfo[col].valign) << "\""
1557                    << write_attribute("width", translate_len(colinfo[col].width))
1558                    << write_attribute("special", colinfo[col].special)
1559                    << write_attribute("varwidth", colinfo[col].varwidth)
1560                    << ">\n";
1561         }
1562         //cerr << "// after cols\n";
1563
1564         for (size_t row = 0; row < rowinfo.size(); ++row) {
1565                 os << "<row"
1566                    << write_attribute("topspace", rowinfo[row].top_space)
1567                    << write_attribute("bottomspace", rowinfo[row].bottom_space)
1568                    << write_attribute("interlinespace", rowinfo[row].interline_space)
1569                    << write_attribute("endhead",
1570                                       rowinfo[row].type == LT_HEAD)
1571                    << write_attribute("endfirsthead",
1572                                       rowinfo[row].type == LT_FIRSTHEAD)
1573                    << write_attribute("endfoot",
1574                                       rowinfo[row].type == LT_FOOT)
1575                    << write_attribute("endlastfoot",
1576                                       rowinfo[row].type == LT_LASTFOOT)
1577                    << write_attribute("newpage", rowinfo[row].newpage)
1578                    << write_attribute("caption", rowinfo[row].caption)
1579                    << ">\n";
1580                 for (size_t col = 0; col < colinfo.size(); ++col) {
1581                         CellInfo const & cell = cellinfo[row][col];
1582                         if (colinfo[col].decimal_point != '\0' && colinfo[col].align != 'd')
1583                                 // These are the second columns in a salign pair. Skip.
1584                                 continue;
1585                         os << "<cell";
1586                         if ((cell.multi == CELL_BEGIN_OF_MULTICOLUMN
1587                                     || cell.multi == CELL_PART_OF_MULTICOLUMN)
1588                                    && colinfo[col].align != 'd')
1589                                 os << " multicolumn=\"" << cell.multi << "\"";
1590                         if (cell.multi == CELL_BEGIN_OF_MULTIROW
1591                             || cell.multi == CELL_PART_OF_MULTIROW)
1592                                 os << " multirow=\"" << cell.multi << "\"";
1593                         os << " alignment=\"" << verbose_align(cell.align)
1594                            << "\""
1595                            << " valignment=\"" << verbose_valign(cell.valign)
1596                            << "\""
1597                            << write_attribute("topline", cell.topline)
1598                            << write_attribute("toplineltrim", cell.topline_ltrim)
1599                            << write_attribute("toplinertrim", cell.topline_rtrim)
1600                            << write_attribute("bottomline", cell.bottomline)
1601                            << write_attribute("bottomlineltrim", cell.bottomline_ltrim)
1602                            << write_attribute("bottomlinertrim", cell.bottomline_rtrim)
1603                            << write_attribute("leftline", cell.leftlines > 0)
1604                            << write_attribute("rightline", cell.rightlines > 0)
1605                            << write_attribute("rotate", cell.rotate)
1606                            << write_attribute("mroffset", cell.mroffset);
1607                         //cerr << "\nrow: " << row << " col: " << col;
1608                         //if (cell.topline)
1609                         //      cerr << " topline=\"true\"";
1610                         //if (cell.bottomline)
1611                         //      cerr << " bottomline=\"true\"";
1612                         os << " usebox=\"none\""
1613                            << write_attribute("width", translate_len(cell.width));
1614                         if (cell.multi != CELL_NORMAL)
1615                                 os << write_attribute("special", cell.special);
1616                         os << ">"
1617                            << "\n\\begin_inset Text\n"
1618                            << cell.content
1619                            << "\n\\end_inset\n"
1620                            << "</cell>\n";
1621                 }
1622                 os << "</row>\n";
1623         }
1624
1625         os << "</lyxtabular>\n";
1626 }
1627
1628
1629
1630
1631 // }])
1632
1633
1634 } // namespace lyx