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