]> git.lyx.org Git - lyx.git/blobdiff - src/tex2lyx/table.cpp
Fix text direction issue for InsetInfo in RTL context
[lyx.git] / src / tex2lyx / table.cpp
index ca3a84cdae6a879e5dbbc3239c5601923a6ee6fd..2007c1c5394dd25ff0236b56991638131e20e88e 100644 (file)
@@ -22,6 +22,7 @@
 #include "support/convert.h"
 #include "support/lstrings.h"
 
+#include <algorithm>
 #include <iostream>
 #include <sstream>
 #include <vector>
@@ -31,15 +32,12 @@ using namespace std;
 
 namespace lyx {
 
-// filled in preamble.cpp
-map<char, int> special_columns;
-
 
 namespace {
 
 class ColInfo {
 public:
-       ColInfo() : align('n'), valign('n'), rightlines(0), leftlines(0) {}
+       ColInfo() : align('n'), valign('n'), rightlines(0), leftlines(0), varwidth(false) {}
        /// column alignment
        char align;
        /// vertical alignment
@@ -52,6 +50,8 @@ public:
        int rightlines;
        /// number of lines on the left
        int leftlines;
+       /// varwidth column
+       bool varwidth;
 };
 
 
@@ -103,14 +103,18 @@ public:
 
 
 /// the numeric values are part of the file format!
-enum Multicolumn {
+enum Multi {
        /// A normal cell
        CELL_NORMAL = 0,
        /// A multicolumn cell. The number of columns is <tt>1 + number
        /// of CELL_PART_OF_MULTICOLUMN cells</tt> that follow directly
-       CELL_BEGIN_OF_MULTICOLUMN = 1,
+       CELL_BEGIN_OF_MULTICOLUMN,
        /// This is a dummy cell (part of a multicolumn cell)
-       CELL_PART_OF_MULTICOLUMN = 2
+       CELL_PART_OF_MULTICOLUMN,
+       ///
+       CELL_BEGIN_OF_MULTIROW,
+       ///
+       CELL_PART_OF_MULTIROW
 };
 
 
@@ -118,11 +122,11 @@ class CellInfo {
 public:
        CellInfo() : multi(CELL_NORMAL), align('n'), valign('n'),
                     leftlines(0), rightlines(0), topline(false),
-                    bottomline(false), rotate(0) {}
+                    bottomline(false), rotate(0), mrxnum(0) {}
        /// cell content
        string content;
        /// multicolumn flag
-       Multicolumn multi;
+       Multi multi;
        /// cell alignment
        char align;
        /// vertical cell alignment
@@ -141,13 +145,17 @@ public:
        string width;
        /// special formatting for multicolumn cells
        string special;
+       /// multirow offset
+       string mroffset;
+       /// number of further multirows
+       int mrxnum;
 };
 
 
 class ltType {
 public:
        // constructor
-       ltType() : topDL(false), bottomDL(false), empty(false) {}
+       ltType() : set(false), topDL(false), bottomDL(false), empty(false) {}
        // we have this header type (is set in the getLT... functions)
        bool set;
        // double borders on top
@@ -209,6 +217,14 @@ string const write_attribute(string const & name, string const & s)
 }
 
 
+string const write_attribute(string const & name, int const & i)
+{
+       // we write only true attribute values so we remove a bit of the
+       // file format bloat for tabulars.
+       return i ? write_attribute(name, convert<string>(i)) : string();
+}
+
+
 /*! rather brutish way to code table structure in a string:
 
 \verbatim
@@ -251,18 +267,23 @@ void ci2special(ColInfo & ci)
                return;
 
        if (!ci.width.empty()) {
+               string arraybackslash;
+               if (ci.varwidth)
+                       arraybackslash = "\\arraybackslash";
                switch (ci.align) {
                case 'l':
-                       ci.special += ">{\\raggedright}";
+                       ci.special += ">{\\raggedright" + arraybackslash + "}";
                        break;
                case 'r':
-                       ci.special += ">{\\raggedleft}";
+                       ci.special += ">{\\raggedleft" + arraybackslash + "}";
                        break;
                case 'c':
-                       ci.special += ">{\\centering}";
+                       ci.special += ">{\\centering" + arraybackslash + "}";
                        break;
                }
-               if (ci.valign == 'n')
+               if (ci.varwidth)
+                       ci.special += 'X';
+               else if (ci.valign == 'n')
                        ci.special += 'p';
                else
                        ci.special += ci.valign;
@@ -316,6 +337,9 @@ void handle_colalign(Parser & p, vector<ColInfo> & colinfo,
                }
 
                switch (t.character()) {
+                       case ' ':
+                               // whitespace, ignore.
+                               break;
                        case 'c':
                        case 'l':
                        case 'r':
@@ -326,6 +350,14 @@ void handle_colalign(Parser & p, vector<ColInfo> & colinfo,
                                colinfo.push_back(next);
                                next = ColInfo();
                                break;
+                       case 'X':
+                               // varwidth column
+                               next.varwidth = true;
+                               if (!next.special.empty())
+                                       ci2special(next);
+                               colinfo.push_back(next);
+                               next = ColInfo();
+                               break;
                        case 'p':
                        case 'b':
                        case 'm':
@@ -359,11 +391,11 @@ void handle_colalign(Parser & p, vector<ColInfo> & colinfo,
                                        // Maybe this can be converted to a
                                        // horizontal alignment setting for
                                        // fixed width columns
-                                       if (s == "\\raggedleft")
+                                       if (s == "\\raggedleft" || s == "\\raggedleft\\arraybackslash")
                                                next.align = 'r';
-                                       else if (s == "\\raggedright")
+                                       else if (s == "\\raggedright" || s == "\\raggedright\\arraybackslash")
                                                next.align = 'l';
-                                       else if (s == "\\centering")
+                                       else if (s == "\\centering" || s == "\\centering\\arraybackslash")
                                                next.align = 'c';
                                        else
                                                next.special = ">{" + s + '}';
@@ -386,6 +418,8 @@ void handle_colalign(Parser & p, vector<ColInfo> & colinfo,
                                break;
                        }
                        case '*': {
+                               if (p.next_token().character() != '{')
+                                       continue;
                                // *{n}{arg} means 'n' columns of type 'arg'
                                string const num = p.verbatim_item();
                                string const arg = p.verbatim_item();
@@ -412,25 +446,22 @@ void handle_colalign(Parser & p, vector<ColInfo> & colinfo,
                                next.special += t.character();
                                next.special += '{' + p.verbatim_item() + '}';
                                break;
-                       default:
+                       default: {
                                // try user defined column types
-                               if (special_columns.find(t.character()) !=
-                                   special_columns.end()) {
-                                       ci2special(next);
-                                       next.special += t.character();
-                                       int const nargs =
-                                               special_columns[t.character()];
-                                       for (int i = 0; i < nargs; ++i)
-                                               next.special += '{' +
-                                                       p.verbatim_item() +
-                                                       '}';
-                                       colinfo.push_back(next);
-                                       next = ColInfo();
-                               } else
-                                       cerr << "Ignoring column specification"
-                                               " '" << t << "'." << endl;
+                               // unknown column types (nargs == -1) are
+                               // assumed to consume no arguments
+                               ci2special(next);
+                               next.special += t.character();
+                               int const nargs =
+                                       preamble.getSpecialTableColumnArguments(t.character());
+                               for (int i = 0; i < nargs; ++i)
+                                       next.special += '{' +
+                                               p.verbatim_item() + '}';
+                               colinfo.push_back(next);
+                               next = ColInfo();
                                break;
                        }
+                       }
        }
 
        // Maybe we have some column separators that need to be added to the
@@ -726,13 +757,13 @@ void parse_table(Parser & p, ostream & os, bool is_long_tabular,
                        }
                }
 
-               else if (t.cat() == catSpace 
+               else if (t.cat() == catSpace
                         || t.cat() == catNewline
-                        || t.cat() == catLetter 
-                        || t.cat() == catSuper 
-                        || t.cat() == catSub 
-                        || t.cat() == catOther 
-                        || t.cat() == catActive 
+                        || t.cat() == catLetter
+                        || t.cat() == catSuper
+                        || t.cat() == catSub
+                        || t.cat() == catOther
+                        || t.cat() == catActive
                         || t.cat() == catParameter)
                        os << t.cs();
 
@@ -778,7 +809,7 @@ void parse_table(Parser & p, ostream & os, bool is_long_tabular,
                        // treat the nested environment as a block, don't
                        // parse &, \\ etc, because they don't belong to our
                        // table if they appear.
-                       os << p.verbatimEnvironment(name);
+                       os << p.ertEnvironment(name);
                        os << "\\end{" << name << '}';
                        active_environments.pop_back();
                }
@@ -831,18 +862,15 @@ void handle_hline_below(RowInfo & ri, vector<CellInfo> & ci)
 
 
 void handle_tabular(Parser & p, ostream & os, string const & name,
-                    string const & tabularwidth, Context & context)
+                   string const & tabularwidth, string const & halign,
+                   Context & context)
 {
-       bool const is_long_tabular(name == "longtable");
+       bool const is_long_tabular(name == "longtable" || name == "xltabular");
        bool booktabs = false;
        string tabularvalignment("middle");
        string posopts = p.getOpt();
        if (!posopts.empty()) {
-               // FIXME: Convert this to ERT
-               if (is_long_tabular)
-                       cerr << "horizontal longtable positioning '"
-                            << posopts << "' ignored\n";
-               else if (posopts == "[t]")
+               if (posopts == "[t]")
                        tabularvalignment = "top";
                else if (posopts == "[b]")
                        tabularvalignment = "bottom";
@@ -1114,19 +1142,69 @@ void handle_tabular(Parser & p, ostream & os, string const & name,
                                     << cells[cell] << "'." << endl;
                                continue;
                        }
-                       Parser p(cells[cell]);
-                       p.skip_spaces();
+                       Parser parse(cells[cell]);
+                       parse.skip_spaces();
                        //cells[cell] << "'\n";
-                       if (p.next_token().cs() == "multicolumn") {
+                       if (parse.next_token().cs() == "multirow") {
+                               // We do not support the vpos arg yet.
+                               if (parse.hasOpt()) {
+                                       string const vpos = parse.getArg('[', ']');
+                                       parse.skip_spaces(true);
+                                       cerr << "Ignoring multirow's vpos arg '"
+                                            << vpos << "'!" << endl;
+                               }
                                // how many cells?
-                               p.get_token();
+                               parse.get_token();
                                size_t const ncells =
-                                       convert<unsigned int>(p.verbatim_item());
+                                       convert<unsigned int>(parse.verbatim_item());
+                               // We do not support the bigstrut arg yet.
+                               if (parse.hasOpt()) {
+                                       string const bs = parse.getArg('[', ']');
+                                       parse.skip_spaces(true);
+                                       cerr << "Ignoring multirow's bigstrut arg '"
+                                            << bs << "'!" << endl;
+                               }
+                               // the width argument
+                               string const width = parse.getArg('{', '}');
+                               // the vmove arg
+                               string vmove;
+                               if (parse.hasOpt()) {
+                                       vmove = parse.getArg('[', ']');
+                                       parse.skip_spaces(true);
+                               }
+
+                               if (width != "*")
+                                       colinfo[col].width = width;
+                               if (!vmove.empty())
+                                       cellinfo[row][col].mroffset = vmove;
+                               cellinfo[row][col].multi = CELL_BEGIN_OF_MULTIROW;
+                               cellinfo[row][col].leftlines  = colinfo[col].leftlines;
+                               cellinfo[row][col].rightlines = colinfo[col].rightlines;
+                               cellinfo[row][col].mrxnum = ncells - 1;
+
+                               ostringstream os2;
+                               parse_text_in_inset(parse, os2, FLAG_ITEM, false, context);
+                               if (!cellinfo[row][col].content.empty()) {
+                                       // This may or may not work in LaTeX,
+                                       // but it does not work in LyX.
+                                       // FIXME: Handle it correctly!
+                                       cerr << "Moving cell content '"
+                                            << cells[cell]
+                                            << "' into a multirow cell. "
+                                               "This will probably not work."
+                                            << endl;
+                               }
+                               cellinfo[row][col].content += os2.str();
+                       } else if (parse.next_token().cs() == "multicolumn") {
+                               // how many cells?
+                               parse.get_token();
+                               size_t const ncells =
+                                       convert<unsigned int>(parse.verbatim_item());
 
                                // special cell properties alignment
                                vector<ColInfo> t;
-                               handle_colalign(p, t, ColInfo());
-                               p.skip_spaces(true);
+                               handle_colalign(parse, t, ColInfo());
+                               parse.skip_spaces(true);
                                ColInfo & ci = t.front();
 
                                // The logic of LyX for multicolumn vertical
@@ -1141,8 +1219,8 @@ void handle_tabular(Parser & p, ostream & os, string const & name,
                                cellinfo[row][col].special    = ci.special;
                                cellinfo[row][col].leftlines  = ci.leftlines;
                                cellinfo[row][col].rightlines = ci.rightlines;
-                               ostringstream os;
-                               parse_text_in_inset(p, os, FLAG_ITEM, false, context);
+                               ostringstream os2;
+                               parse_text_in_inset(parse, os2, FLAG_ITEM, false, context);
                                if (!cellinfo[row][col].content.empty()) {
                                        // This may or may not work in LaTeX,
                                        // but it does not work in LyX.
@@ -1153,18 +1231,30 @@ void handle_tabular(Parser & p, ostream & os, string const & name,
                                                "This will probably not work."
                                             << endl;
                                }
-                               cellinfo[row][col].content += os.str();
+                               cellinfo[row][col].content += os2.str();
 
                                // add dummy cells for multicol
-                               for (size_t i = 0; i < ncells - 1 && col < colinfo.size(); ++i) {
+                               for (size_t i = 0; i < ncells - 1; ++i) {
                                        ++col;
+                                       if (col >= colinfo.size()) {
+                                               cerr << "The cell '"
+                                                       << cells[cell]
+                                                       << "' specifies "
+                                                       << convert<string>(ncells)
+                                                       << " columns while the table has only "
+                                                       << convert<string>(colinfo.size())
+                                                       << " columns!"
+                                                       << " Therefore the surplus columns will be ignored."
+                                                       << endl;
+                                               break;
+                                       }
                                        cellinfo[row][col].multi = CELL_PART_OF_MULTICOLUMN;
                                        cellinfo[row][col].align = 'c';
                                }
 
                        } else if (col == 0 && colinfo.size() > 1 &&
                                   is_long_tabular &&
-                                  p.next_token().cs() == "caption") {
+                                  parse.next_token().cs() == "caption") {
                                // longtable caption support in LyX is a hack:
                                // Captions require a row of their own with
                                // the caption flag set to true, having only
@@ -1187,19 +1277,51 @@ void handle_tabular(Parser & p, ostream & os, string const & name,
                                cells.resize(1);
                                cellinfo[row][col].align      = colinfo[col].align;
                                cellinfo[row][col].multi      = CELL_BEGIN_OF_MULTICOLUMN;
-                               ostringstream os;
-                               parse_text_in_inset(p, os, FLAG_CELL, false, context);
-                               cellinfo[row][col].content += os.str();
+                               ostringstream os2;
+                               parse_text_in_inset(parse, os2, FLAG_CELL, false, context);
+                               cellinfo[row][col].content += os2.str();
                                // add dummy multicolumn cells
                                for (size_t c = 1; c < colinfo.size(); ++c)
                                        cellinfo[row][c].multi = CELL_PART_OF_MULTICOLUMN;
                        } else {
+                               bool turn = false;
+                               int rotate = 0;
+                               if (parse.next_token().cs() == "begin") {
+                                       parse.pushPosition();
+                                       parse.get_token();
+                                       string const env = parse.getArg('{', '}');
+                                       if (env == "sideways" || env == "turn") {
+                                               string angle = "90";
+                                               if (env == "turn") {
+                                                       turn = true;
+                                                       angle = parse.getArg('{', '}');
+                                               }
+                                               active_environments.push_back(env);
+                                               parse.ertEnvironment(env);
+                                               active_environments.pop_back();
+                                               parse.skip_spaces();
+                                               if (!parse.good() && support::isStrInt(angle))
+                                                       rotate = convert<int>(angle);
+                                       }
+                                       parse.popPosition();
+                               }
                                cellinfo[row][col].leftlines  = colinfo[col].leftlines;
                                cellinfo[row][col].rightlines = colinfo[col].rightlines;
                                cellinfo[row][col].align      = colinfo[col].align;
-                               ostringstream os;
-                               parse_text_in_inset(p, os, FLAG_CELL, false, context);
-                               cellinfo[row][col].content += os.str();
+                               ostringstream os2;
+                               if (rotate != 0) {
+                                       cellinfo[row][col].rotate = rotate;
+                                       parse.get_token();
+                                       active_environments.push_back(parse.getArg('{', '}'));
+                                       if (turn)
+                                               parse.getArg('{', '}');
+                                       parse_text_in_inset(parse, os2, FLAG_END, false, context);
+                                       active_environments.pop_back();
+                                       preamble.registerAutomaticallyLoadedPackage("rotating");
+                               } else {
+                                       parse_text_in_inset(parse, os2, FLAG_CELL, false, context);
+                               }
+                               cellinfo[row][col].content += os2.str();
                        }
                }
 
@@ -1222,13 +1344,23 @@ void handle_tabular(Parser & p, ostream & os, string const & name,
        // and cellinfo.
        // Unfortunately LyX has some limitations that we need to work around.
 
-       // Convert cells with special content to multicolumn cells
-       // (LyX ignores the special field for non-multicolumn cells).
+       // Some post work
        for (size_t row = 0; row < rowinfo.size(); ++row) {
                for (size_t col = 0; col < cellinfo[row].size(); ++col) {
+                       // Convert cells with special content to multicolumn cells
+                       // (LyX ignores the special field for non-multicolumn cells).
                        if (cellinfo[row][col].multi == CELL_NORMAL &&
                            !cellinfo[row][col].special.empty())
                                cellinfo[row][col].multi = CELL_BEGIN_OF_MULTICOLUMN;
+                       // Add multirow dummy cells
+                       if (row > 1 && (cellinfo[row - 1][col].multi == CELL_PART_OF_MULTIROW
+                                       || cellinfo[row - 1][col].multi == CELL_BEGIN_OF_MULTIROW)
+                                   && cellinfo[row - 1][col].mrxnum > 0) {
+                               // add dummy cells for multirow
+                               cellinfo[row][col].multi = CELL_PART_OF_MULTIROW;
+                               cellinfo[row][col].align = 'c';
+                               cellinfo[row][col].mrxnum = cellinfo[row - 1][col].mrxnum - 1;
+                       }
                }
        }
 
@@ -1258,21 +1390,36 @@ void handle_tabular(Parser & p, ostream & os, string const & name,
                                        cellinfo[row][col].rightlines = colinfo[col].rightlines;
                                if (col > 0 && cellinfo[row][col-1].multi == CELL_NORMAL)
                                        cellinfo[row][col].leftlines = colinfo[col].leftlines;
+                       } else if (cellinfo[row][col].multi == CELL_BEGIN_OF_MULTIROW) {
+                               size_t s = row + 1;
+                               while (s < rowinfo.size() &&
+                                      cellinfo[s][col].multi == CELL_PART_OF_MULTIROW)
+                                       s++;
+                               if (s < cellinfo[row].size() &&
+                                   cellinfo[s][col].multi != CELL_BEGIN_OF_MULTIROW)
+                                       cellinfo[row][col].bottomline = rowinfo[row].bottomline;
+                               if (row > 0 && cellinfo[row - 1][col].multi == CELL_NORMAL)
+                                       cellinfo[row][col].topline = rowinfo[row].topline;
                        }
                }
        }
 
        if (booktabs)
                preamble.registerAutomaticallyLoadedPackage("booktabs");
-       if (is_long_tabular)
+       if (name == "longtable")
                preamble.registerAutomaticallyLoadedPackage("longtable");
+       else if (name == "xltabular")
+               preamble.registerAutomaticallyLoadedPackage("xltabular");
+       else if (name == "tabularx")
+               preamble.registerAutomaticallyLoadedPackage("tabularx");
 
        //cerr << "// output what we have\n";
        // output what we have
+       string const rotate = "0";
        os << "\n<lyxtabular version=\"3\" rows=\"" << rowinfo.size()
           << "\" columns=\"" << colinfo.size() << "\">\n";
        os << "<features"
-          << write_attribute("rotate", "0")
+          << write_attribute("rotate", rotate)
           << write_attribute("booktabs", booktabs)
           << write_attribute("islongtable", is_long_tabular);
        if (is_long_tabular) {
@@ -1286,10 +1433,12 @@ void handle_tabular(Parser & p, ostream & os, string const & name,
                   << write_attribute("lastFootTopDL", endlastfoot.topDL)
                   << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
                   << write_attribute("lastFootEmpty", endlastfoot.empty);
+               if (!halign.empty())
+                       os << write_attribute("longtabularalignment", halign);
        } else
-               os << write_attribute("tabularvalignment", tabularvalignment)
-                  << write_attribute("tabularwidth", tabularwidth);
-       os << ">\n";
+               os << write_attribute("tabularvalignment", tabularvalignment);
+                  
+       os << write_attribute("tabularwidth", tabularwidth) << ">\n";
 
        //cerr << "// after header\n";
        for (size_t col = 0; col < colinfo.size(); ++col) {
@@ -1299,6 +1448,7 @@ void handle_tabular(Parser & p, ostream & os, string const & name,
                   << verbose_valign(colinfo[col].valign) << "\""
                   << write_attribute("width", translate_len(colinfo[col].width))
                   << write_attribute("special", colinfo[col].special)
+                  << write_attribute("varwidth", colinfo[col].varwidth)
                   << ">\n";
        }
        //cerr << "// after cols\n";
@@ -1322,8 +1472,12 @@ void handle_tabular(Parser & p, ostream & os, string const & name,
                for (size_t col = 0; col < colinfo.size(); ++col) {
                        CellInfo const & cell = cellinfo[row][col];
                        os << "<cell";
-                       if (cell.multi != CELL_NORMAL)
+                       if (cell.multi == CELL_BEGIN_OF_MULTICOLUMN
+                           || cell.multi == CELL_PART_OF_MULTICOLUMN)
                                os << " multicolumn=\"" << cell.multi << "\"";
+                       if (cell.multi == CELL_BEGIN_OF_MULTIROW
+                           || cell.multi == CELL_PART_OF_MULTIROW)
+                               os << " multirow=\"" << cell.multi << "\"";
                        os << " alignment=\"" << verbose_align(cell.align)
                           << "\""
                           << " valignment=\"" << verbose_valign(cell.valign)
@@ -1332,7 +1486,8 @@ void handle_tabular(Parser & p, ostream & os, string const & name,
                           << write_attribute("bottomline", cell.bottomline)
                           << write_attribute("leftline", cell.leftlines > 0)
                           << write_attribute("rightline", cell.rightlines > 0)
-                          << write_attribute("rotate", cell.rotate);
+                          << write_attribute("rotate", cell.rotate)
+                          << write_attribute("mroffset", cell.mroffset);
                        //cerr << "\nrow: " << row << " col: " << col;
                        //if (cell.topline)
                        //      cerr << " topline=\"true\"";