3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
22 #include "support/lassert.h"
23 #include "support/convert.h"
24 #include "support/lstrings.h"
41 ColInfo() : align('n'), valign('n'), rightlines(0), leftlines(0),
42 varwidth(false), decimal_point('\0'), vcolumn(false) {}
45 /// vertical alignment
49 /// special column alignment
51 /// number of lines on the right
53 /// number of lines on the left
64 /// row type for longtables
71 /// part of head on first page
75 /// part of foot on last page
82 RowInfo() : topline(false), bottomline(false), type(LT_NORMAL),
83 caption(false), newpage(false) {}
84 /// Does this row have any special setting?
87 return topline || bottomline || !top_space.empty() ||
88 !bottom_space.empty() || !interline_space.empty() ||
89 type != LT_NORMAL || caption || newpage;
91 /// horizontal line above
93 /// horizontal line below
95 /// Extra space between the top line and this row
97 /// Extra space between this row and the bottom line
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.)
104 /// row for a caption
106 /// row for a newpage
111 /// the numeric values are part of the file format!
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,
121 CELL_BEGIN_OF_MULTIROW,
123 CELL_PART_OF_MULTIROW
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) {}
140 /// vertical cell alignment
142 /// number of lines on the left
144 /// number of lines on the right
146 /// do we have a line above?
148 /// do we have a line below?
150 /// Left trimming of top line
152 /// Right trimming of top line
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?
160 /// width for multicolumn cells
162 /// special formatting for multicolumn cells
166 /// number of further multirows
174 ltType() : set(false), topDL(false), bottomDL(false), empty(false) {}
175 // we have this header type (is set in the getLT... functions)
177 // double borders on top
179 // double borders on bottom
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!
188 /// translate a horizontal alignment (as stored in ColInfo and CellInfo) to LyX
189 inline char const * verbose_align(char c)
206 /// translate a vertical alignment (as stored in ColInfo and CellInfo) to LyX
207 inline char const * verbose_valign(char c)
209 // The default value for no special alignment is "top".
222 // stripped down from tabluar.C. We use it currently only for bools and
224 string const write_attribute(string const & name, bool const & b)
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();
232 string const write_attribute(string const & name, string const & s)
234 return s.empty() ? string() : ' ' + name + "=\"" + s + '"';
238 string const write_attribute(string const & name, int const & i)
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();
246 /*! rather brutish way to code table structure in a string:
251 \multicolumn{2}{c}{4} & 5 //
257 gets "translated" to:
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
267 char const TAB = '\001';
268 char const LINE = '\002';
269 char const HLINE = '\004';
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
278 void ci2special(ColInfo & ci)
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
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';
298 if (!ci.width.empty()) {
299 string arraybackslash;
301 arraybackslash = "\\arraybackslash";
304 ci.special += ">{\\raggedright" + arraybackslash + "}";
307 ci.special += ">{\\raggedleft" + arraybackslash + "}";
310 ci.special += ">{\\centering" + arraybackslash + "}";
315 else if (ci.varwidth)
317 else if (ci.valign == 'n')
320 ci.special += ci.valign;
321 ci.special += '{' + ci.width + '}';
324 ci.special += ci.align;
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)
331 ci.leftlines = min(ci.leftlines, 1);
332 ci.rightlines = min(ci.rightlines, 1);
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.
345 void handle_colalign(Parser & p, vector<ColInfo> & colinfo,
346 ColInfo const & start)
348 if (p.get_token().cat() != catBegin)
349 cerr << "Wrong syntax for table column alignment.\n"
350 "Expected '{', got '" << p.curr_token().asInput()
353 ColInfo next = start;
354 for (Token t = p.get_token(); p.good() && t.cat() != catEnd;
357 cerr << "t: " << t << " c: '" << t.character() << "'\n";
360 // We cannot handle comments here
361 if (t.cat() == catComment) {
362 if (t.cs().empty()) {
366 cerr << "Ignoring comment: " << t.asInput();
370 switch (t.character()) {
372 // whitespace, ignore.
377 // new column, horizontal aligned
378 next.align = t.character();
379 if (!next.special.empty()) {
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;
387 next.decimal_point = '\0';
390 colinfo.push_back(next);
395 next.varwidth = true;
396 if (!next.special.empty())
398 colinfo.push_back(next);
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()) {
412 colinfo.push_back(next);
419 // new column, vertical aligned box
420 next.valign = t.character();
421 next.width = p.verbatim_item();
422 if (!next.special.empty()) {
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;
430 next.decimal_point = '\0';
433 colinfo.push_back(next);
438 if (colinfo.empty()) {
439 if (next.special.empty())
443 } else if (colinfo.back().special.empty())
444 ++colinfo.back().rightlines;
445 else if (next.special.empty() && p.next_token().cat() != catEnd)
448 colinfo.back().special += '|';
451 // text before the next column
452 string const s = trimSpaceAndEol(p.verbatim_item());
453 if (next.special.empty() &&
455 // Maybe this can be converted to a
456 // horizontal alignment setting for
457 // fixed width columns
458 if (s == "\\raggedleft" || s == "\\raggedleft\\arraybackslash")
460 else if (s == "\\raggedright" || s == "\\raggedright\\arraybackslash")
462 else if (s == "\\centering" || s == "\\centering\\arraybackslash")
465 next.special = ">{" + s + '}';
467 next.special += ">{" + s + '}';
471 // text after the last column
472 string const s = trimSpaceAndEol(p.verbatim_item());
474 // This is not possible in LaTeX.
475 cerr << "Ignoring separator '<{"
476 << s << "}'." << endl;
478 ColInfo & ci = colinfo.back();
480 ci.special += "<{" + s + '}';
485 if (p.next_token().character() != '{')
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) {
493 for (size_t i = 0; i < n; ++i)
497 handle_colalign(p2, colinfo, next);
500 cerr << "Ignoring column specification"
501 " '*{" << num << "}{"
502 << arg << "}'." << endl;
507 // text instead of the column spacing
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();
519 // try user defined column types
520 // unknown column types (nargs == -1) are
521 // assumed to consume no arguments
523 next.special += t.character();
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);
536 // Maybe we have some column separators that need to be added to the
539 if (!next.special.empty()) {
540 ColInfo & ci = colinfo.back();
542 ci.special += next.special;
543 next.special.erase();
549 * Move the left and right lines and alignment settings of the column \p ci
550 * to the special field if necessary.
552 void fix_colalign(ColInfo & ci)
554 if (ci.leftlines > 1 || ci.rightlines > 1)
560 * LyX can't handle more than one vertical line at the left or right side
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.
565 void fix_colalign(vector<ColInfo> & colinfo)
567 // Try to move extra leftlines to the previous column.
568 // We do this only if both special fields are empty, otherwise we
569 // can't tell whether the result will be the same.
570 for (size_t col = 0; col < colinfo.size(); ++col) {
571 if (colinfo[col].leftlines > 1 &&
572 colinfo[col].special.empty() && col > 0 &&
573 colinfo[col - 1].rightlines == 0 &&
574 colinfo[col - 1].special.empty()) {
575 ++colinfo[col - 1].rightlines;
576 --colinfo[col].leftlines;
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;
590 // Move the lines and alignment settings to the special field if
592 for (auto & col : colinfo)
598 * Parse hlines and similar stuff.
599 * \returns whether the token \p t was parsed
601 bool parse_hlines(Parser & p, Token const & t, string & hlines,
602 bool is_long_tabular)
604 LASSERT(t.cat() == catEscape, return false);
606 if (t.cs() == "hline" || t.cs() == "toprule" || t.cs() == "midrule" ||
607 t.cs() == "bottomrule")
608 hlines += '\\' + t.cs();
610 else if (t.cs() == "cline")
611 hlines += "\\cline{" + p.verbatim_item() + '}';
613 else if (t.cs() == "cmidrule") {
616 // We do not support the optional height argument
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();
624 if (support::contains(trim, "{"))
626 hlines += "\\cmidrule" + trim + "{" + range + "}";
628 hlines += "\\cmidrule{" + range + '}';
631 else if (t.cs() == "addlinespace") {
634 bool const hasArgument(p.getFullArg('{', '}').first);
637 hlines += "\\addlinespace{" + p.verbatim_item() + '}';
639 hlines += "\\addlinespace";
642 else if (is_long_tabular && t.cs() == "newpage")
643 hlines += "\\newpage";
652 /// Position in a row
654 /// At the very beginning, before the first token
656 /// After the first token and before any column token
658 /// After the first column token. Comments and whitespace are only
659 /// treated as tokens in this position
661 /// After the first non-column token at the end
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().
672 void parse_table(Parser & p, ostream & os, bool is_long_tabular,
673 RowPosition & pos, unsigned flags)
675 // table structure commands such as \hline
678 // comments that occur at places where we can't handle them
682 Token const & t = p.get_token();
685 debugToken(cerr, t, flags);
688 // comments and whitespace in hlines
691 case IN_HLINES_START:
693 if (t.cat() == catComment) {
698 // We can't handle comments here,
699 // store them for later use
700 comments += t.asInput();
702 } else if (t.cat() == catSpace ||
703 t.cat() == catNewline) {
704 // whitespace is irrelevant here, we
705 // need to recognize hline stuff
714 // We need to handle structure stuff first in order to
715 // determine whether we need to output a HLINE separator
716 // before the row or not.
717 if (t.cat() == catEscape) {
718 if (parse_hlines(p, t, hlines, is_long_tabular)) {
721 pos = IN_HLINES_START;
726 case IN_HLINES_START:
733 else if (t.cs() == "tabularnewline" ||
737 cerr << "Warning: Converting TeX "
738 "'\\cr' to LaTeX '\\\\'."
740 // stuff before the line break
741 os << comments << HLINE << hlines << HLINE
743 //cerr << "hlines: " << hlines << endl;
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();
759 // these commands are implicit line
761 os << comments << HLINE << hlines
768 pos = IN_HLINES_START;
770 case IN_HLINES_START:
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.
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
786 os << hlines << HLINE << comments;
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.
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;
812 // If we come here we have normal cell content
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
822 // This does only work because parse_math outputs TeX
823 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
825 p.get_token(); // skip the second '$' token
827 // simple $...$ stuff
830 // This does only work because parse_math outputs TeX
831 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
836 else if (t.cat() == catSpace
837 || t.cat() == catNewline
838 || t.cat() == catLetter
839 || t.cat() == catSuper
841 || t.cat() == catOther
842 || t.cat() == catActive
843 || t.cat() == catParameter)
846 else if (t.cat() == catBegin) {
848 parse_table(p, os, is_long_tabular, pos,
853 else if (t.cat() == catEnd) {
854 if (flags & FLAG_BRACE_LAST)
856 cerr << "unexpected '}'\n";
859 else if (t.cat() == catAlign) {
864 else if (t.cat() == catComment)
867 else if (t.cs() == "(") {
869 // This does only work because parse_math outputs TeX
870 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
874 else if (t.cs() == "[") {
876 // This does only work because parse_math outputs TeX
877 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
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();
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() + "}");
902 p.error("found 'end' unexpectedly");
909 // We can have comments if the last line is incomplete
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"
921 void handle_hline_above(RowInfo & ri, vector<CellInfo> & ci)
924 for (auto & col : ci)
929 void handle_hline_below(RowInfo & ri, vector<CellInfo> & ci)
931 ri.bottomline = true;
932 for (auto & col : ci)
933 col.bottomline = true;
937 void parse_cell_content(ostringstream & os2, Parser & parse, unsigned int flags, Context & newcontext,
938 vector< vector<CellInfo> > & cellinfo, vector<ColInfo> & colinfo,
939 size_t const row, size_t const col)
943 bool varwidth = false;
944 if (parse.next_token().cs() == "begin") {
945 parse.pushPosition();
947 string const env = parse.getArg('{', '}');
948 if (env == "sideways" || env == "turn") {
952 angle = parse.getArg('{', '}');
954 active_environments.push_back(env);
955 parse.ertEnvironment(env);
956 active_environments.pop_back();
958 if (!parse.good() && support::isStrInt(angle))
959 rotate = convert<int>(angle);
960 } else if (env == "cellvarwidth") {
961 active_environments.push_back(env);
962 parse.ertEnvironment(env);
963 active_environments.pop_back();
970 cellinfo[row][col].rotate = rotate;
972 active_environments.push_back(parse.getArg('{', '}'));
974 parse.getArg('{', '}');
975 parse_text_in_inset(parse, os2, FLAG_END, false, newcontext);
976 active_environments.pop_back();
977 preamble.registerAutomaticallyLoadedPackage("rotating");
978 } else if (varwidth) {
980 active_environments.push_back(parse.getArg('{', '}'));
983 cellinfo[row][col].valign = parse.getArg('[', ']')[1];
984 newcontext.in_table_cell = true;
985 parse_text_in_inset(parse, os2, FLAG_END, false, newcontext);
986 if (cellinfo[row][col].multi == CELL_NORMAL)
987 colinfo[col].align = newcontext.cell_align;
989 cellinfo[row][col].align = newcontext.cell_align;
990 active_environments.pop_back();
991 preamble.registerAutomaticallyLoadedPackage("varwidth");
993 parse_text_in_inset(parse, os2, flags, false, newcontext);
998 } // anonymous namespace
1001 void handle_tabular(Parser & p, ostream & os, string const & name,
1002 string const & tabularwidth, string const & halign,
1003 Context const & context)
1005 Context newcontext = context;
1006 bool const is_long_tabular(name == "longtable" || name == "xltabular");
1007 bool booktabs = false;
1008 string tabularvalignment("middle");
1009 string posopts = p.getOpt();
1010 if (!posopts.empty()) {
1011 if (posopts == "[t]")
1012 tabularvalignment = "top";
1013 else if (posopts == "[b]")
1014 tabularvalignment = "bottom";
1016 cerr << "vertical tabular positioning '"
1017 << posopts << "' ignored\n";
1020 vector<ColInfo> colinfo;
1022 // handle column formatting
1023 handle_colalign(p, colinfo, ColInfo());
1024 fix_colalign(colinfo);
1026 // first scan of cells
1027 // use table mode to keep it minimal-invasive
1028 // not exactly what's TeX doing...
1029 vector<string> lines;
1031 RowPosition rowpos = ROW_START;
1032 parse_table(p, ss, is_long_tabular, rowpos, FLAG_END);
1033 split(ss.str(), lines, LINE);
1035 vector< vector<CellInfo> > cellinfo(lines.size());
1036 vector<RowInfo> rowinfo(lines.size());
1037 ltType endfirsthead;
1043 //cerr << "// split into rows\n";
1044 for (size_t row = 0; row < rowinfo.size();) {
1047 cellinfo[row].resize(colinfo.size());
1048 bool deletelastrow = false;
1051 vector<string> dummy;
1052 //cerr << "\n########### LINE: " << lines[row] << "########\n";
1053 split(lines[row], dummy, HLINE);
1055 // handle horizontal line fragments
1056 // we do only expect this for a last line without '\\'
1057 if (dummy.size() != 3) {
1058 if ((dummy.size() != 1 && dummy.size() != 2) ||
1059 row != rowinfo.size() - 1)
1060 cerr << "unexpected dummy size: " << dummy.size()
1061 << " content: " << lines[row] << "\n";
1064 lines[row] = dummy[1];
1066 //cerr << "line: " << row << " above 0: " << dummy[0] << "\n";
1067 //cerr << "line: " << row << " below 2: " << dummy[2] << "\n";
1068 //cerr << "line: " << row << " cells 1: " << dummy[1] << "\n";
1070 for (int i = 0; i <= 2; i += 2) {
1071 //cerr << " reading from line string '" << dummy[i] << "'\n";
1072 Parser p1(dummy[size_type(i)]);
1074 Token t = p1.get_token();
1075 //cerr << "read token: " << t << "\n";
1076 if (t.cs() == "hline" || t.cs() == "toprule" ||
1077 t.cs() == "midrule" ||
1078 t.cs() == "bottomrule") {
1079 if (t.cs() != "hline")
1082 if (rowinfo[row].topline) {
1083 if (row > 0) // extra bottomline above
1084 handle_hline_below(rowinfo[row - 1], cellinfo[row - 1]);
1086 cerr << "dropping extra "
1088 //cerr << "below row: " << row-1 << endl;
1090 handle_hline_above(rowinfo[row], cellinfo[row]);
1091 //cerr << "above row: " << row << endl;
1094 //cerr << "below row: " << row << endl;
1095 handle_hline_below(rowinfo[row], cellinfo[row]);
1097 } else if (t.cs() == "cline" || t.cs() == "cmidrule") {
1099 if (t.cs() == "cmidrule") {
1101 trim = p1.getFullParentheseArg();
1103 string arg = p1.verbatim_item();
1104 //cerr << "read " << t.cs() << " arg: '" << arg << "', trim: '" << trim << "'\n";
1105 vector<string> cols;
1106 split(arg, cols, '-');
1108 size_t from = convert<unsigned int>(cols[0]);
1110 cerr << "Could not parse "
1111 << t.cs() << " start column."
1114 // 1 based index -> 0 based
1116 if (from >= colinfo.size()) {
1117 cerr << t.cs() << " starts at "
1118 "non existing column "
1119 << (from + 1) << endl;
1120 from = colinfo.size() - 1;
1122 size_t to = convert<unsigned int>(cols[1]);
1124 cerr << "Could not parse "
1125 << t.cs() << " end column."
1128 // 1 based index -> 0 based
1130 if (to >= colinfo.size()) {
1131 cerr << t.cs() << " ends at "
1132 "non existing column "
1133 << (to + 1) << endl;
1134 to = colinfo.size() - 1;
1136 for (size_t col = from; col <= to; ++col) {
1137 //cerr << "row: " << row << " col: " << col << " i: " << i << endl;
1139 rowinfo[row].topline = true;
1140 cellinfo[row][col].topline = true;
1141 if (support::contains(trim, 'l') && col == from) {
1142 //rowinfo[row].topline_ltrim = true;
1143 cellinfo[row][col].topline_ltrim = true;
1145 else if (support::contains(trim, 'r') && col == to) {
1146 //rowinfo[row].topline_rtrim = true;
1147 cellinfo[row][col].topline_rtrim = true;
1150 rowinfo[row].bottomline = true;
1151 cellinfo[row][col].bottomline = true;
1152 if (support::contains(trim, 'l') && col == from) {
1153 //rowinfo[row].bottomline_ltrim = true;
1154 cellinfo[row][col].bottomline_ltrim = true;
1156 else if (support::contains(trim, 'r') && col == to) {
1157 //rowinfo[row].bottomline_rtrim = true;
1158 cellinfo[row][col].bottomline_rtrim = true;
1162 } else if (t.cs() == "addlinespace") {
1164 string const opt = p.next_token().cat() == catBegin ?
1165 p.verbatim_item() : string();
1168 rowinfo[row].top_space = "default";
1170 rowinfo[row].top_space = translate_len(opt);
1171 } else if (rowinfo[row].bottomline) {
1173 rowinfo[row].bottom_space = "default";
1175 rowinfo[row].bottom_space = translate_len(opt);
1178 rowinfo[row].interline_space = "default";
1180 rowinfo[row].interline_space = translate_len(opt);
1182 } else if (t.cs() == "endhead") {
1184 endhead.empty = true;
1186 rowinfo[row].type = LT_HEAD;
1187 for (int r = row - 1; r >= 0; --r) {
1188 if (rowinfo[r].type != LT_NORMAL)
1190 rowinfo[r].type = LT_HEAD;
1191 endhead.empty = false;
1194 } else if (t.cs() == "endfirsthead") {
1196 endfirsthead.empty = true;
1198 rowinfo[row].type = LT_FIRSTHEAD;
1199 for (int r = row - 1; r >= 0; --r) {
1200 if (rowinfo[r].type != LT_NORMAL)
1202 rowinfo[r].type = LT_FIRSTHEAD;
1203 endfirsthead.empty = false;
1205 endfirsthead.set = true;
1206 } else if (t.cs() == "endfoot") {
1208 endfoot.empty = true;
1210 rowinfo[row].type = LT_FOOT;
1211 for (int r = row - 1; r >= 0; --r) {
1212 if (rowinfo[r].type != LT_NORMAL)
1214 rowinfo[r].type = LT_FOOT;
1215 endfoot.empty = false;
1218 } else if (t.cs() == "endlastfoot") {
1220 endlastfoot.empty = true;
1222 rowinfo[row].type = LT_LASTFOOT;
1223 for (int r = row - 1; r >= 0; --r) {
1224 if (rowinfo[r].type != LT_NORMAL)
1226 rowinfo[r].type = LT_LASTFOOT;
1227 endlastfoot.empty = false;
1229 endlastfoot.set = true;
1230 } else if (t.cs() == "newpage") {
1233 rowinfo[row - 1].newpage = true;
1235 // This does not work in LaTeX
1241 rowinfo[row].newpage = true;
1243 cerr << "unexpected line token: " << t << endl;
1248 // LyX ends headers and footers always with \tabularnewline.
1249 // This causes one additional row in the output.
1250 // If the last row of a header/footer is empty, we can work
1251 // around that by removing it.
1253 RowInfo test = rowinfo[row-1];
1254 test.type = LT_NORMAL;
1255 if (lines[row-1].empty() && !test.special()) {
1256 switch (rowinfo[row-1].type) {
1258 if (rowinfo[row].type != LT_FIRSTHEAD &&
1259 rowinfo[row-2].type == LT_FIRSTHEAD)
1260 deletelastrow = true;
1263 if (rowinfo[row].type != LT_HEAD &&
1264 rowinfo[row-2].type == LT_HEAD)
1265 deletelastrow = true;
1268 if (rowinfo[row].type != LT_FOOT &&
1269 rowinfo[row-2].type == LT_FOOT)
1270 deletelastrow = true;
1273 if (rowinfo[row].type != LT_LASTFOOT &&
1274 rowinfo[row-2].type == LT_LASTFOOT)
1275 deletelastrow = true;
1283 if (deletelastrow) {
1284 lines.erase(lines.begin() + (row - 1));
1285 rowinfo.erase(rowinfo.begin() + (row - 1));
1286 cellinfo.erase(cellinfo.begin() + (row - 1));
1291 vector<string> cells;
1292 split(lines[row], cells, TAB);
1293 for (size_t col = 0, cell = 0; cell < cells.size();
1295 //cerr << "cell content: '" << cells[cell] << "'\n";
1296 if (col >= colinfo.size()) {
1297 // This does not work in LaTeX
1298 cerr << "Ignoring extra cell '"
1299 << cells[cell] << "'." << endl;
1302 string cellcont = cells[cell];
1303 // For decimal cells, ass the content of the second one to the first one
1305 if (colinfo[col].decimal_point != '\0' && colinfo[col].align == 'd' && cell < cells.size() - 1)
1306 cellcont += colinfo[col].decimal_point + cells[cell + 1];
1307 Parser parse(cellcont);
1308 parse.skip_spaces();
1309 //cells[cell] << "'\n";
1310 if (parse.next_token().cs() == "multirow") {
1311 // We do not support the vpos arg yet.
1312 if (parse.hasOpt()) {
1313 string const vpos = parse.getArg('[', ']');
1314 parse.skip_spaces(true);
1315 cerr << "Ignoring multirow's vpos arg '"
1316 << vpos << "'!" << endl;
1320 size_t const ncells =
1321 convert<unsigned int>(parse.verbatim_item());
1322 // We do not support the bigstrut arg yet.
1323 if (parse.hasOpt()) {
1324 string const bs = parse.getArg('[', ']');
1325 parse.skip_spaces(true);
1326 cerr << "Ignoring multirow's bigstrut arg '"
1327 << bs << "'!" << endl;
1329 // the width argument
1330 string const width = parse.getArg('{', '}');
1333 if (parse.hasOpt()) {
1334 vmove = parse.getArg('[', ']');
1335 parse.skip_spaces(true);
1338 if (width != "*" && width != "=")
1339 colinfo[col].width = width;
1341 cellinfo[row][col].mroffset = vmove;
1342 cellinfo[row][col].multi = CELL_BEGIN_OF_MULTIROW;
1343 cellinfo[row][col].leftlines = colinfo[col].leftlines;
1344 cellinfo[row][col].rightlines = colinfo[col].rightlines;
1345 cellinfo[row][col].mrxnum = ncells - 1;
1348 parse.get_token();// skip {
1349 parse_cell_content(os2, parse, FLAG_BRACE_LAST, newcontext,
1352 parse.get_token();// skip }
1353 if (!cellinfo[row][col].content.empty()) {
1354 // This may or may not work in LaTeX,
1355 // but it does not work in LyX.
1356 // FIXME: Handle it correctly!
1357 cerr << "Moving cell content '"
1359 << "' into a multirow cell. "
1360 "This will probably not work."
1363 cellinfo[row][col].content += os2.str();
1364 } else if (parse.next_token().cs() == "multicolumn") {
1367 size_t const ncells =
1368 convert<unsigned int>(parse.verbatim_item());
1370 // special cell properties alignment
1372 handle_colalign(parse, t, ColInfo());
1373 parse.skip_spaces(true);
1374 ColInfo & ci = t.front();
1376 // The logic of LyX for multicolumn vertical
1377 // lines is too complicated to reproduce it
1378 // here (see LyXTabular::TeXCellPreamble()).
1379 // Therefore we simply put everything in the
1383 cellinfo[row][col].multi = CELL_BEGIN_OF_MULTICOLUMN;
1384 cellinfo[row][col].align = ci.align;
1385 cellinfo[row][col].special = ci.special;
1386 cellinfo[row][col].leftlines = ci.leftlines;
1387 cellinfo[row][col].rightlines = ci.rightlines;
1389 parse.get_token();// skip {
1390 parse_cell_content(os2, parse, FLAG_BRACE_LAST, newcontext,
1393 parse.get_token();// skip }
1394 if (!cellinfo[row][col].content.empty()) {
1395 // This may or may not work in LaTeX,
1396 // but it does not work in LyX.
1397 // FIXME: Handle it correctly!
1398 cerr << "Moving cell content '"
1400 << "' into a multicolumn cell. "
1401 "This will probably not work."
1404 cellinfo[row][col].content += os2.str();
1406 // add dummy cells for multicol
1407 for (size_t i = 0; i < ncells - 1; ++i) {
1409 if (col >= colinfo.size()) {
1410 cerr << "The cell '"
1413 << convert<string>(ncells)
1414 << " columns while the table has only "
1415 << convert<string>(colinfo.size())
1417 << " Therefore the surplus columns will be ignored."
1421 cellinfo[row][col].multi = CELL_PART_OF_MULTICOLUMN;
1422 cellinfo[row][col].align = 'c';
1425 } else if (col == 0 && colinfo.size() > 1 &&
1427 parse.next_token().cs() == "caption") {
1428 // longtable caption support in LyX is a hack:
1429 // Captions require a row of their own with
1430 // the caption flag set to true, having only
1431 // one multicolumn cell. The contents of that
1432 // cell must contain exactly one caption inset
1433 // and nothing else.
1434 // Fortunately, the caption flag is only needed
1435 // for tables with more than one column.
1436 rowinfo[row].caption = true;
1437 for (size_t c = 1; c < cells.size(); ++c) {
1438 if (!cells[c].empty()) {
1439 cerr << "Moving cell content '"
1441 << "' into the caption cell. "
1442 "This will probably not work."
1444 cells[0] += cells[c];
1448 cellinfo[row][col].align = colinfo[col].align;
1449 cellinfo[row][col].multi = CELL_BEGIN_OF_MULTICOLUMN;
1451 parse_text_in_inset(parse, os2, FLAG_CELL, false, newcontext);
1452 cellinfo[row][col].content += os2.str();
1453 // add dummy multicolumn cells
1454 for (size_t c = 1; c < colinfo.size(); ++c)
1455 cellinfo[row][c].multi = CELL_PART_OF_MULTICOLUMN;
1456 } else if (col == 0 && colinfo.size() > 1 &&
1458 parse.next_token().cs() == "caption") {
1459 // longtable caption support in LyX is a hack:
1460 // Captions require a row of their own with
1461 // the caption flag set to true, having only
1462 // one multicolumn cell. The contents of that
1463 // cell must contain exactly one caption inset
1464 // and nothing else.
1465 // Fortunately, the caption flag is only needed
1466 // for tables with more than one column.
1467 rowinfo[row].caption = true;
1468 for (size_t c = 1; c < cells.size(); ++c) {
1469 if (!cells[c].empty()) {
1470 cerr << "Moving cell content '"
1472 << "' into the caption cell. "
1473 "This will probably not work."
1475 cells[0] += cells[c];
1479 cellinfo[row][col].align = colinfo[col].align;
1480 cellinfo[row][col].multi = CELL_BEGIN_OF_MULTICOLUMN;
1482 parse_text_in_inset(parse, os2, FLAG_CELL, false, newcontext);
1483 cellinfo[row][col].content += os2.str();
1484 // add dummy multicolumn cells
1485 for (size_t c = 1; c < colinfo.size(); ++c)
1486 cellinfo[row][c].multi = CELL_PART_OF_MULTICOLUMN;
1489 parse_cell_content(os2, parse, FLAG_CELL, newcontext,
1492 cellinfo[row][col].leftlines = colinfo[col].leftlines;
1493 cellinfo[row][col].rightlines = colinfo[col].rightlines;
1494 cellinfo[row][col].align = colinfo[col].align;
1495 cellinfo[row][col].content += os2.str();
1499 //cerr << "// handle almost empty last row what we have\n";
1500 // handle almost empty last row
1501 if (row && lines[row].empty() && row + 1 == rowinfo.size()) {
1502 //cerr << "remove empty last line\n";
1503 if (rowinfo[row].topline)
1504 rowinfo[row - 1].bottomline = true;
1505 for (size_t col = 0; col < colinfo.size(); ++col)
1506 if (cellinfo[row][col].topline)
1507 cellinfo[row - 1][col].bottomline = true;
1514 // Now we have the table structure and content in rowinfo, colinfo
1516 // Unfortunately LyX has some limitations that we need to work around.
1519 for (size_t row = 0; row < rowinfo.size(); ++row) {
1520 for (size_t col = 0; col < cellinfo[row].size(); ++col) {
1521 // Convert cells with special content to multicolumn cells
1522 // (LyX ignores the special field for non-multicolumn cells).
1523 if (cellinfo[row][col].multi == CELL_NORMAL &&
1524 !cellinfo[row][col].special.empty())
1525 cellinfo[row][col].multi = CELL_BEGIN_OF_MULTICOLUMN;
1526 // Add multirow dummy cells
1527 if (row > 1 && (cellinfo[row - 1][col].multi == CELL_PART_OF_MULTIROW
1528 || cellinfo[row - 1][col].multi == CELL_BEGIN_OF_MULTIROW)
1529 && cellinfo[row - 1][col].mrxnum > 0) {
1530 // add dummy cells for multirow
1531 cellinfo[row][col].multi = CELL_PART_OF_MULTIROW;
1532 cellinfo[row][col].align = 'c';
1533 cellinfo[row][col].mrxnum = cellinfo[row - 1][col].mrxnum - 1;
1538 // Distribute lines from rows/columns to cells
1539 // The code was stolen from convert_tablines() in lyx2lyx/lyx_1_6.py.
1540 // Each standard cell inherits the settings of the corresponding
1541 // rowinfo/colinfo. This works because all cells with individual
1542 // settings were converted to multicolumn cells above.
1543 // Each multicolumn cell inherits the settings of the rowinfo/colinfo
1544 // corresponding to the first column of the multicolumn cell (default
1545 // of the multicol package). This works because the special field
1546 // overrides the line fields.
1547 for (size_t row = 0; row < rowinfo.size(); ++row) {
1548 for (size_t col = 0; col < cellinfo[row].size(); ++col) {
1549 if (cellinfo[row][col].multi == CELL_NORMAL) {
1550 cellinfo[row][col].topline = rowinfo[row].topline;
1551 cellinfo[row][col].bottomline = rowinfo[row].bottomline;
1552 cellinfo[row][col].leftlines = colinfo[col].leftlines;
1553 cellinfo[row][col].rightlines = colinfo[col].rightlines;
1554 } else if (cellinfo[row][col].multi == CELL_BEGIN_OF_MULTICOLUMN) {
1556 while (s < cellinfo[row].size() &&
1557 cellinfo[row][s].multi == CELL_PART_OF_MULTICOLUMN)
1559 if (s < cellinfo[row].size() &&
1560 cellinfo[row][s].multi != CELL_BEGIN_OF_MULTICOLUMN)
1561 cellinfo[row][col].rightlines = colinfo[col].rightlines;
1562 if (col > 0 && cellinfo[row][col-1].multi == CELL_NORMAL)
1563 cellinfo[row][col].leftlines = colinfo[col].leftlines;
1564 } else if (cellinfo[row][col].multi == CELL_BEGIN_OF_MULTIROW) {
1566 while (s < rowinfo.size() &&
1567 cellinfo[s][col].multi == CELL_PART_OF_MULTIROW)
1569 if (s < cellinfo[row].size() &&
1570 cellinfo[s][col].multi != CELL_BEGIN_OF_MULTIROW)
1571 cellinfo[row][col].bottomline = rowinfo[row].bottomline;
1572 if (row > 0 && cellinfo[row - 1][col].multi == CELL_NORMAL)
1573 cellinfo[row][col].topline = rowinfo[row].topline;
1579 preamble.registerAutomaticallyLoadedPackage("booktabs");
1580 if (name == "longtable")
1581 preamble.registerAutomaticallyLoadedPackage("longtable");
1582 else if (name == "xltabular")
1583 preamble.registerAutomaticallyLoadedPackage("xltabular");
1584 else if (name == "tabularx")
1585 preamble.registerAutomaticallyLoadedPackage("tabularx");
1587 //cerr << "// output what we have\n";
1588 // output what we have
1589 size_type cols = colinfo.size();
1590 for (auto const & col : colinfo) {
1591 if (col.decimal_point != '\0' && col.align != 'd')
1594 os << "\n<lyxtabular version=\"3\" rows=\"" << rowinfo.size()
1595 << "\" columns=\"" << cols << "\">\n";
1597 << write_attribute("rotate", context.tablerotation)
1598 << write_attribute("booktabs", booktabs)
1599 << write_attribute("islongtable", is_long_tabular);
1600 if (is_long_tabular) {
1601 os << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1602 << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1603 << write_attribute("firstHeadEmpty", endfirsthead.empty)
1604 << write_attribute("headTopDL", endhead.topDL)
1605 << write_attribute("headBottomDL", endhead.bottomDL)
1606 << write_attribute("footTopDL", endfoot.topDL)
1607 << write_attribute("footBottomDL", endfoot.bottomDL)
1608 << write_attribute("lastFootTopDL", endlastfoot.topDL)
1609 << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1610 << write_attribute("lastFootEmpty", endlastfoot.empty);
1611 if (!halign.empty())
1612 os << write_attribute("longtabularalignment", halign);
1614 os << write_attribute("tabularvalignment", tabularvalignment);
1616 os << write_attribute("tabularwidth", tabularwidth) << ">\n";
1618 //cerr << "// after header\n";
1619 for (auto const & col : colinfo) {
1620 if (col.decimal_point != '\0' && col.align != 'd')
1622 os << "<column alignment=\""
1623 << verbose_align(col.align) << "\"";
1624 if (col.decimal_point != '\0')
1625 os << " decimal_point=\"" << col.decimal_point << "\"";
1626 os << " valignment=\""
1627 << verbose_valign(col.valign) << "\""
1628 << write_attribute("width", translate_len(col.width))
1629 << write_attribute("special", col.special)
1630 << write_attribute("varwidth", col.varwidth)
1633 //cerr << "// after cols\n";
1635 for (size_t row = 0; row < rowinfo.size(); ++row) {
1637 << write_attribute("topspace", rowinfo[row].top_space)
1638 << write_attribute("bottomspace", rowinfo[row].bottom_space)
1639 << write_attribute("interlinespace", rowinfo[row].interline_space)
1640 << write_attribute("endhead",
1641 rowinfo[row].type == LT_HEAD)
1642 << write_attribute("endfirsthead",
1643 rowinfo[row].type == LT_FIRSTHEAD)
1644 << write_attribute("endfoot",
1645 rowinfo[row].type == LT_FOOT)
1646 << write_attribute("endlastfoot",
1647 rowinfo[row].type == LT_LASTFOOT)
1648 << write_attribute("newpage", rowinfo[row].newpage)
1649 << write_attribute("caption", rowinfo[row].caption)
1651 for (size_t col = 0; col < colinfo.size(); ++col) {
1652 CellInfo const & cell = cellinfo[row][col];
1653 if (colinfo[col].decimal_point != '\0' && colinfo[col].align != 'd')
1654 // These are the second columns in a salign pair. Skip.
1657 if ((cell.multi == CELL_BEGIN_OF_MULTICOLUMN
1658 || cell.multi == CELL_PART_OF_MULTICOLUMN)
1659 && colinfo[col].align != 'd')
1660 os << " multicolumn=\"" << cell.multi << "\"";
1661 if (cell.multi == CELL_BEGIN_OF_MULTIROW
1662 || cell.multi == CELL_PART_OF_MULTIROW)
1663 os << " multirow=\"" << cell.multi << "\"";
1664 os << " alignment=\"" << verbose_align(cell.align)
1666 << " valignment=\"" << verbose_valign(cell.valign)
1668 << write_attribute("topline", cell.topline)
1669 << write_attribute("toplineltrim", cell.topline_ltrim)
1670 << write_attribute("toplinertrim", cell.topline_rtrim)
1671 << write_attribute("bottomline", cell.bottomline)
1672 << write_attribute("bottomlineltrim", cell.bottomline_ltrim)
1673 << write_attribute("bottomlinertrim", cell.bottomline_rtrim)
1674 << write_attribute("leftline", cell.leftlines > 0)
1675 << write_attribute("rightline", cell.rightlines > 0)
1676 << write_attribute("rotate", cell.rotate)
1677 << write_attribute("mroffset", cell.mroffset);
1678 //cerr << "\nrow: " << row << " col: " << col;
1680 // cerr << " topline=\"true\"";
1681 //if (cell.bottomline)
1682 // cerr << " bottomline=\"true\"";
1683 os << " usebox=\"none\""
1684 << write_attribute("width", translate_len(cell.width));
1685 if (cell.multi != CELL_NORMAL)
1686 os << write_attribute("special", cell.special);
1688 << "\n\\begin_inset Text\n"
1690 << "\n\\end_inset\n"
1696 os << "</lyxtabular>\n";