]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
InsetTabular.cpp: whitespace
[lyx.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Matthias Ettrich
8  * \author José Matos
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Jürgen Vigna
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "InsetTabular.h"
21
22 #include "buffer_funcs.h"
23 #include "Buffer.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
27 #include "Counters.h"
28 #include "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Language.h"
34 #include "LaTeXFeatures.h"
35 #include "Lexer.h"
36 #include "LyXFunc.h"
37 #include "LyXRC.h"
38 #include "MetricsInfo.h"
39 #include "OutputParams.h"
40 #include "paragraph_funcs.h"
41 #include "Paragraph.h"
42 #include "ParagraphParameters.h"
43 #include "ParIterator.h"
44 #include "TextClass.h"
45 #include "TextMetrics.h"
46
47 #include "frontends/Application.h"
48 #include "frontends/alert.h"
49 #include "frontends/Clipboard.h"
50 #include "frontends/Painter.h"
51 #include "frontends/Selection.h"
52
53 #include "support/convert.h"
54 #include "support/debug.h"
55 #include "support/docstream.h"
56 #include "support/FileName.h"
57 #include "support/gettext.h"
58 #include "support/lassert.h"
59 #include "support/lstrings.h"
60
61 #include <boost/scoped_ptr.hpp>
62
63 #include <sstream>
64 #include <iostream>
65 #include <limits>
66 #include <cstring>
67
68 using namespace std;
69 using namespace lyx::support;
70
71 using boost::shared_ptr;
72 using boost::dynamic_pointer_cast;
73
74
75 namespace lyx {
76
77 using cap::dirtyTabularStack;
78 using cap::tabularStackDirty;
79
80 using graphics::PreviewLoader;
81
82 using frontend::Painter;
83 using frontend::Clipboard;
84
85 namespace Alert = frontend::Alert;
86
87
88 namespace {
89
90 int const ADD_TO_HEIGHT = 2; // in cell
91 int const ADD_TO_TABULAR_WIDTH = 6; // horiz space before and after the table
92 int const default_line_space = 10; // ?
93 int const WIDTH_OF_LINE = 5; // space between double lines
94
95
96 ///
97 boost::scoped_ptr<Tabular> paste_tabular;
98
99
100 struct TabularFeature {
101         Tabular::Feature action;
102         string feature;
103 };
104
105
106 TabularFeature tabularFeature[] =
107 {
108         { Tabular::APPEND_ROW, "append-row" },
109         { Tabular::APPEND_COLUMN, "append-column" },
110         { Tabular::DELETE_ROW, "delete-row" },
111         { Tabular::DELETE_COLUMN, "delete-column" },
112         { Tabular::COPY_ROW, "copy-row" },
113         { Tabular::COPY_COLUMN, "copy-column" },
114         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top" },
115         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
116         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
117         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
118         { Tabular::ALIGN_LEFT, "align-left" },
119         { Tabular::ALIGN_RIGHT, "align-right" },
120         { Tabular::ALIGN_CENTER, "align-center" },
121         { Tabular::ALIGN_BLOCK, "align-block" },
122         { Tabular::VALIGN_TOP, "valign-top" },
123         { Tabular::VALIGN_BOTTOM, "valign-bottom" },
124         { Tabular::VALIGN_MIDDLE, "valign-middle" },
125         { Tabular::M_ALIGN_LEFT, "m-align-left" },
126         { Tabular::M_ALIGN_RIGHT, "m-align-right" },
127         { Tabular::M_ALIGN_CENTER, "m-align-center" },
128         { Tabular::M_VALIGN_TOP, "m-valign-top" },
129         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
130         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle" },
131         { Tabular::MULTICOLUMN, "multicolumn" },
132         { Tabular::SET_ALL_LINES, "set-all-lines" },
133         { Tabular::UNSET_ALL_LINES, "unset-all-lines" },
134         { Tabular::SET_LONGTABULAR, "set-longtabular" },
135         { Tabular::UNSET_LONGTABULAR, "unset-longtabular" },
136         { Tabular::SET_PWIDTH, "set-pwidth" },
137         { Tabular::SET_MPWIDTH, "set-mpwidth" },
138         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
139         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
140         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular" },
141         { Tabular::SET_ROTATE_CELL, "set-rotate-cell" },
142         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
143         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell" },
144         { Tabular::SET_USEBOX, "set-usebox" },
145         { Tabular::SET_LTHEAD, "set-lthead" },
146         { Tabular::UNSET_LTHEAD, "unset-lthead" },
147         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
148         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead" },
149         { Tabular::SET_LTFOOT, "set-ltfoot" },
150         { Tabular::UNSET_LTFOOT, "unset-ltfoot" },
151         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot" },
152         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot" },
153         { Tabular::SET_LTNEWPAGE, "set-ltnewpage" },
154         { Tabular::TOGGLE_LTCAPTION, "toggle-ltcaption" },
155         { Tabular::SET_SPECIAL_COLUMN, "set-special-column" },
156         { Tabular::SET_SPECIAL_MULTI, "set-special-multi" },
157         { Tabular::SET_BOOKTABS, "set-booktabs" },
158         { Tabular::UNSET_BOOKTABS, "unset-booktabs" },
159         { Tabular::SET_TOP_SPACE, "set-top-space" },
160         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space" },
161         { Tabular::SET_INTERLINE_SPACE, "set-interline-space" },
162         { Tabular::SET_BORDER_LINES, "set-border-lines" },
163         { Tabular::TABULAR_VALIGN_TOP, "tabular-valign-top"},
164         { Tabular::TABULAR_VALIGN_MIDDLE, "tabular-valign-middle"},
165         { Tabular::TABULAR_VALIGN_BOTTOM, "tabular-valign-bottom"},
166         { Tabular::LONGTABULAR_ALIGN_LEFT, "longtabular-align-left" },
167         { Tabular::LONGTABULAR_ALIGN_CENTER, "longtabular-align-center" },
168         { Tabular::LONGTABULAR_ALIGN_RIGHT, "longtabular-align-right" },        
169         { Tabular::LAST_ACTION, "" }
170 };
171
172
173 class FeatureEqual : public unary_function<TabularFeature, bool> {
174 public:
175         FeatureEqual(Tabular::Feature feature)
176                 : feature_(feature) {}
177         bool operator()(TabularFeature const & tf) const {
178                 return tf.action == feature_;
179         }
180 private:
181         Tabular::Feature feature_;
182 };
183
184
185 template <class T>
186 string const write_attribute(string const & name, T const & t)
187 {
188         string const s = tostr(t);
189         return s.empty() ? s : " " + name + "=\"" + s + "\"";
190 }
191
192 template <>
193 string const write_attribute(string const & name, string const & t)
194 {
195         return t.empty() ? t : " " + name + "=\"" + t + "\"";
196 }
197
198
199 template <>
200 string const write_attribute(string const & name, docstring const & t)
201 {
202         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
203 }
204
205
206 template <>
207 string const write_attribute(string const & name, bool const & b)
208 {
209         // we write only true attribute values so we remove a bit of the
210         // file format bloat for tabulars.
211         return b ? write_attribute(name, convert<string>(b)) : string();
212 }
213
214
215 template <>
216 string const write_attribute(string const & name, int const & i)
217 {
218         // we write only true attribute values so we remove a bit of the
219         // file format bloat for tabulars.
220         return i ? write_attribute(name, convert<string>(i)) : string();
221 }
222
223
224 template <>
225 string const write_attribute(string const & name, Tabular::idx_type const & i)
226 {
227         // we write only true attribute values so we remove a bit of the
228         // file format bloat for tabulars.
229         return i ? write_attribute(name, convert<string>(i)) : string();
230 }
231
232
233 template <>
234 string const write_attribute(string const & name, Length const & value)
235 {
236         // we write only the value if we really have one same reson as above.
237         return value.zero() ? string() : write_attribute(name, value.asString());
238 }
239
240
241 string const tostr(LyXAlignment const & num)
242 {
243         switch (num) {
244         case LYX_ALIGN_NONE:
245                 return "none";
246         case LYX_ALIGN_BLOCK:
247                 return "block";
248         case LYX_ALIGN_LEFT:
249                 return "left";
250         case LYX_ALIGN_CENTER:
251                 return "center";
252         case LYX_ALIGN_RIGHT:
253                 return "right";
254         case LYX_ALIGN_LAYOUT:
255                 return "layout";
256         case LYX_ALIGN_SPECIAL:
257                 return "special";
258         }
259         return string();
260 }
261
262
263 string const tostr(Tabular::HAlignment const & num)
264 {
265         switch (num) {
266         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
267                 return "left";
268         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
269                 return "center";
270         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
271                 return "right";
272         }
273         return string();
274 }
275
276
277 string const tostr(Tabular::VAlignment const & num)
278 {
279         switch (num) {
280         case Tabular::LYX_VALIGN_TOP:
281                 return "top";
282         case Tabular::LYX_VALIGN_MIDDLE:
283                 return "middle";
284         case Tabular::LYX_VALIGN_BOTTOM:
285                 return "bottom";
286         }
287         return string();
288 }
289
290
291 string const tostr(Tabular::BoxType const & num)
292 {
293         switch (num) {
294         case Tabular::BOX_NONE:
295                 return "none";
296         case Tabular::BOX_PARBOX:
297                 return "parbox";
298         case Tabular::BOX_MINIPAGE:
299                 return "minipage";
300         }
301         return string();
302 }
303
304
305 // I would have liked a fromstr template a lot better. (Lgb)
306 bool string2type(string const str, LyXAlignment & num)
307 {
308         if (str == "none")
309                 num = LYX_ALIGN_NONE;
310         else if (str == "block")
311                 num = LYX_ALIGN_BLOCK;
312         else if (str == "left")
313                 num = LYX_ALIGN_LEFT;
314         else if (str == "center")
315                 num = LYX_ALIGN_CENTER;
316         else if (str == "right")
317                 num = LYX_ALIGN_RIGHT;
318         else
319                 return false;
320         return true;
321 }
322
323
324 bool string2type(string const str, Tabular::HAlignment & num)
325 {
326         if (str == "left")
327                 num = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
328         else if (str == "center" )
329                 num = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
330         else if (str == "right")
331                 num = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
332         else
333                 return false;
334         return true;
335 }
336
337
338 bool string2type(string const str, Tabular::VAlignment & num)
339 {
340         if (str == "top")
341                 num = Tabular::LYX_VALIGN_TOP;
342         else if (str == "middle" )
343                 num = Tabular::LYX_VALIGN_MIDDLE;
344         else if (str == "bottom")
345                 num = Tabular::LYX_VALIGN_BOTTOM;
346         else
347                 return false;
348         return true;
349 }
350
351
352 bool string2type(string const str, Tabular::BoxType & num)
353 {
354         if (str == "none")
355                 num = Tabular::BOX_NONE;
356         else if (str == "parbox")
357                 num = Tabular::BOX_PARBOX;
358         else if (str == "minipage")
359                 num = Tabular::BOX_MINIPAGE;
360         else
361                 return false;
362         return true;
363 }
364
365
366 bool string2type(string const str, bool & num)
367 {
368         if (str == "true")
369                 num = true;
370         else if (str == "false")
371                 num = false;
372         else
373                 return false;
374         return true;
375 }
376
377
378 bool getTokenValue(string const & str, char const * token, string & ret)
379 {
380         ret.erase();
381         size_t token_length = strlen(token);
382         size_t pos = str.find(token);
383
384         if (pos == string::npos || pos + token_length + 1 >= str.length()
385                 || str[pos + token_length] != '=')
386                 return false;
387         pos += token_length + 1;
388         char ch = str[pos];
389         if (ch != '"' && ch != '\'') { // only read till next space
390                 ret += ch;
391                 ch = ' ';
392         }
393         while (pos < str.length() - 1 && str[++pos] != ch)
394                 ret += str[pos];
395
396         return true;
397 }
398
399
400 bool getTokenValue(string const & str, char const * token, docstring & ret)
401 {
402         string tmp;
403         bool const success = getTokenValue(str, token, tmp);
404         ret = from_utf8(tmp);
405         return success;
406 }
407
408
409 bool getTokenValue(string const & str, char const * token, int & num)
410 {
411         string tmp;
412         num = 0;
413         if (!getTokenValue(str, token, tmp))
414                 return false;
415         num = convert<int>(tmp);
416         return true;
417 }
418
419
420 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
421 {
422         string tmp;
423         return getTokenValue(str, token, tmp) && string2type(tmp, num);
424 }
425
426
427 bool getTokenValue(string const & str, char const * token,
428                                    Tabular::HAlignment & num)
429 {
430         string tmp;
431         return getTokenValue(str, token, tmp) && string2type(tmp, num);
432 }
433
434
435 bool getTokenValue(string const & str, char const * token,
436                                    Tabular::VAlignment & num)
437 {
438         string tmp;
439         return getTokenValue(str, token, tmp) && string2type(tmp, num);
440 }
441
442
443 bool getTokenValue(string const & str, char const * token,
444                                    Tabular::BoxType & num)
445 {
446         string tmp;
447         return getTokenValue(str, token, tmp) && string2type(tmp, num);
448 }
449
450
451 bool getTokenValue(string const & str, char const * token, bool & flag)
452 {
453         // set the flag always to false as this should be the default for bools
454         // not in the file-format.
455         flag = false;
456         string tmp;
457         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
458 }
459
460
461 bool getTokenValue(string const & str, char const * token, Length & len)
462 {
463         // set the length to be zero() as default as this it should be if not
464         // in the file format.
465         len = Length();
466         string tmp;
467         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
468 }
469
470
471 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
472 {
473         len = Length();
474         flag = false;
475         string tmp;
476         if (!getTokenValue(str, token, tmp))
477                 return false;
478         if (tmp == "default") {
479                 flag = true;
480                 return  true;
481         }
482         return isValidLength(tmp, &len);
483 }
484
485
486 void l_getline(istream & is, string & str)
487 {
488         str.erase();
489         while (str.empty()) {
490                 getline(is, str);
491                 if (!str.empty() && str[str.length() - 1] == '\r')
492                         str.erase(str.length() - 1);
493         }
494 }
495
496 } // namespace
497
498
499 string const featureAsString(Tabular::Feature feature)
500 {
501         TabularFeature * end = tabularFeature +
502                 sizeof(tabularFeature) / sizeof(TabularFeature);
503         TabularFeature * it = find_if(tabularFeature, end,
504                                            FeatureEqual(feature));
505         return (it == end) ? string() : it->feature;
506 }
507
508
509
510 /////////////////////////////////////////////////////////////////////
511 //
512 // Tabular
513 //
514 /////////////////////////////////////////////////////////////////////
515
516
517 Tabular::CellData::CellData(Buffer & buf)
518         : cellno(0),
519           width(0),
520           multicolumn(Tabular::CELL_NORMAL),
521           alignment(LYX_ALIGN_CENTER),
522           valignment(LYX_VALIGN_TOP),
523           top_line(false),
524           bottom_line(false),
525           left_line(false),
526           right_line(false),
527           usebox(BOX_NONE),
528           rotate(false),
529           inset(new InsetTableCell(buf))
530 {
531         inset->setBuffer(const_cast<Buffer &>(buf));
532 }
533
534
535 Tabular::CellData::CellData(CellData const & cs)
536         : cellno(cs.cellno),
537           width(cs.width),
538           multicolumn(cs.multicolumn),
539           alignment(cs.alignment),
540           valignment(cs.valignment),
541           top_line(cs.top_line),
542           bottom_line(cs.bottom_line),
543           left_line(cs.left_line),
544           right_line(cs.right_line),
545           usebox(cs.usebox),
546           rotate(cs.rotate),
547           align_special(cs.align_special),
548           p_width(cs.p_width),
549           inset(dynamic_cast<InsetTableCell *>(cs.inset->clone()))
550 {
551 }
552
553 Tabular::CellData & Tabular::CellData::operator=(CellData cs)
554 {
555         swap(cs);
556         return *this;
557 }
558
559 void Tabular::CellData::swap(CellData & rhs)
560 {
561         std::swap(cellno, rhs.cellno);
562         std::swap(width, rhs.width);
563         std::swap(multicolumn, rhs.multicolumn);
564         std::swap(alignment, rhs.alignment);
565         std::swap(valignment, rhs.valignment);
566         std::swap(top_line, rhs.top_line);
567         std::swap(bottom_line, rhs.bottom_line);
568         std::swap(left_line, rhs.left_line);
569         std::swap(right_line, rhs.right_line);
570         std::swap(usebox, rhs.usebox);
571         std::swap(rotate, rhs.rotate);
572         std::swap(align_special, rhs.align_special);
573         p_width.swap(rhs.p_width);
574         inset.swap(rhs.inset);
575 }
576
577
578 Tabular::RowData::RowData()
579         : ascent(0),
580           descent(0),
581           top_space_default(false),
582           bottom_space_default(false),
583           interline_space_default(false),
584           endhead(false),
585           endfirsthead(false),
586           endfoot(false),
587           endlastfoot(false),
588           newpage(false),
589           caption(false)
590 {}
591
592
593 Tabular::ColumnData::ColumnData()
594         : alignment(LYX_ALIGN_CENTER),
595           valignment(LYX_VALIGN_TOP),
596           width(0)
597 {
598 }
599
600
601 Tabular::ltType::ltType()
602         : topDL(false),
603           bottomDL(false),
604           empty(false)
605 {}
606
607
608 Tabular::Tabular(Buffer & buffer, row_type rows_arg, col_type columns_arg)
609 {
610         init(buffer, rows_arg, columns_arg);
611 }
612
613
614 void Tabular::setBuffer(Buffer & buffer)
615 {
616         buffer_ = &buffer;
617         size_t row_count = row_info.size();
618         size_t column_count = column_info.size();
619         // set silly default lines
620         for (row_type i = 0; i < row_count; ++i)
621                 for (col_type j = 0; j < column_count; ++j)
622                         cell_info[i][j].inset->setBuffer(*buffer_);
623 }
624
625
626 // activates all lines and sets all widths to 0
627 void Tabular::init(Buffer & buf, row_type rows_arg,
628                       col_type columns_arg)
629 {
630         buffer_ = &buf;
631         row_info = row_vector(rows_arg);
632         column_info = column_vector(columns_arg);
633         cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf)));
634         row_info.reserve(10);
635         column_info.reserve(10);
636         cell_info.reserve(100);
637         updateIndexes();
638         is_long_tabular = false;
639         tabular_valignment = LYX_VALIGN_MIDDLE;
640         longtabular_alignment = LYX_LONGTABULAR_ALIGN_CENTER;
641         rotate = false;
642         use_booktabs = false;
643         size_t row_count = row_info.size();
644         size_t column_count = column_info.size();
645         // set silly default lines
646         for (row_type i = 0; i < row_count; ++i)
647                 for (col_type j = 0; j < column_count; ++j) {
648                         cell_info[i][j].inset->setBuffer(*buffer_);
649                         cell_info[i][j].top_line = true;
650                         cell_info[i][j].left_line = true;
651                         cell_info[i][j].bottom_line = i == 0 || i == row_count - 1;
652                         cell_info[i][j].right_line = j == column_count - 1;
653                 }
654 }
655
656
657 void Tabular::appendRow(idx_type const cell)
658 {
659         BufferParams const & bp = buffer().params();
660         row_type const row = cellRow(cell);
661
662         row_vector::iterator rit = row_info.begin() + row;
663         row_info.insert(rit, RowData());
664         // now set the values of the row before
665         row_info[row] = row_info[row + 1];
666
667         row_type const nrows = row_info.size();
668         col_type const ncols = column_info.size();
669
670         cell_vvector old(nrows - 1);
671         for (row_type i = 0; i < nrows - 1; ++i)
672                 swap(cell_info[i], old[i]);
673
674         cell_info = cell_vvector(nrows, cell_vector(ncols, CellData(buffer())));
675
676         for (row_type i = 0; i <= row; ++i)
677                 swap(cell_info[i], old[i]);
678         for (row_type i = row + 2; i < nrows; ++i)
679                 swap(cell_info[i], old[i - 1]);
680
681         updateIndexes();
682         for (col_type c = 0; c < ncols; ++c) {
683                 // inherit line settings
684                 idx_type const i = cellIndex(row + 1, c);
685                 idx_type const j = cellIndex(row, c);
686                 setLeftLine(i, leftLine(j));
687                 setRightLine(i, rightLine(j));
688                 setTopLine(i, topLine(j));
689                 if (topLine(j) && bottomLine(j)) {
690                         setBottomLine(i, true);
691                         setBottomLine(j, false);
692                 }
693                 // mark track changes
694                 if (bp.trackChanges)
695                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
696         }
697 }
698
699
700 void Tabular::deleteRow(row_type const row)
701 {
702         // Not allowed to delete last row
703         if (row_info.size() == 1)
704                 return;
705
706         row_info.erase(row_info.begin() + row);
707         cell_info.erase(cell_info.begin() + row);
708         updateIndexes();
709 }
710
711
712 void Tabular::copyRow(row_type const row)
713 {
714         row_info.insert(row_info.begin() + row, row_info[row]);
715         cell_info.insert(cell_info.begin() + row, cell_info[row]);
716
717         if (buffer().params().trackChanges)
718                 for (col_type j = 0; j < column_info.size(); ++j)
719                         cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
720
721         updateIndexes();
722 }
723
724
725 void Tabular::appendColumn(idx_type const cell)
726 {
727         col_type const c = cellColumn(cell);
728         column_vector::iterator cit = column_info.begin() + c + 1;
729         column_info.insert(cit, ColumnData());
730         row_type const nrows = row_info.size();
731         // set the column values of the column before
732         column_info[c + 1] = column_info[c];
733
734         for (row_type r = 0; r < nrows; ++r) {
735                 cell_info[r].insert(cell_info[r].begin() + c + 1, 
736                         CellData(buffer()));
737 #if 0
738 // FIXME: This code does not work. It deletes the cell's content and
739 // it triggers an assertion if the cursor is at pos > 0.
740                 if (cell_info[r][c].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
741                         cell_info[r][c + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
742                 else
743                         cell_info[r][c + 1].multicolumn = cell_info[r][c].multicolumn;
744 #endif
745         }
746         updateIndexes();
747         for (row_type r = 0; r < nrows; ++r) {
748                 // inherit line settings
749                 idx_type const i = cellIndex(r, c + 1);
750                 idx_type const j = cellIndex(r, c);
751                 setBottomLine(i, bottomLine(j));
752                 setTopLine(i, topLine(j));
753                 setLeftLine(i, leftLine(j));
754                 if (rightLine(j) && rightLine(j)) {
755                         setRightLine(i, true);
756                         setRightLine(j, false);
757                 }
758                 //
759                 cellInfo(i).inset->clear();
760                 if (buffer().params().trackChanges)
761                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
762         }
763 }
764
765
766 void Tabular::deleteColumn(col_type const column)
767 {
768         // Not allowed to delete last column
769         if (column_info.size() == 1)
770                 return;
771
772         size_t const row_count = row_info.size();
773         for (row_type i = 0; i < row_count; ++i) {
774                 // Care about multicolumn cells
775                 if (column + 1 < column_info.size() &&
776                     cell_info[i][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
777                     cell_info[i][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
778                         cell_info[i][column + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
779                 }
780                 cell_info[i].erase(cell_info[i].begin() + column);
781         }
782         column_info.erase(column_info.begin() + column);
783         updateIndexes();
784 }
785
786
787 void Tabular::copyColumn(col_type const column)
788 {
789         BufferParams const & bp = buffer().params();
790         column_info.insert(column_info.begin() + column, column_info[column]);
791
792         size_t row_count = row_info.size();
793         for (row_type i = 0; i < row_count; ++i)
794                 cell_info[i].insert(cell_info[i].begin() + column, cell_info[i][column]);
795
796         if (bp.trackChanges)
797                 for (row_type i = 0; i < row_count; ++i)
798                         cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
799         updateIndexes();
800 }
801
802
803 void Tabular::updateIndexes()
804 {
805         col_type ncols = column_info.size();
806         row_type nrows = row_info.size();
807         numberofcells = 0;
808         for (row_type row = 0; row < nrows; ++row)
809                 for (col_type column = 0; column < ncols; ++column) {
810                         if (!isPartOfMultiColumn(row, column))
811                                 ++numberofcells;
812                         cell_info[row][column].cellno = numberofcells - 1;
813                 }
814
815         rowofcell.resize(numberofcells);
816         columnofcell.resize(numberofcells);
817         idx_type i = 0;
818         for (row_type row = 0; row < nrows; ++row)
819                 for (col_type column = 0; column < ncols; ++column) {
820                         if (isPartOfMultiColumn(row, column))
821                                 continue;
822                         rowofcell[i] = row;
823                         columnofcell[i] = column;
824                         setFixedWidth(row, column);
825                         updateContentAlignment(row, column);
826                         ++i;
827                 }
828 }
829
830
831 Tabular::idx_type Tabular::numberOfCellsInRow(idx_type const cell) const
832 {
833         row_type const row = cellRow(cell);
834         idx_type result = 0;
835         for (col_type i = 0; i < column_info.size(); ++i)
836                 if (cell_info[row][i].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
837                         ++result;
838         return result;
839 }
840
841
842 bool Tabular::topLine(idx_type const cell) const
843 {
844         return cellInfo(cell).top_line;
845 }
846
847
848 bool Tabular::bottomLine(idx_type const cell) const
849 {
850         return cellInfo(cell).bottom_line;
851 }
852
853
854 bool Tabular::leftLine(idx_type cell) const
855 {
856         if (use_booktabs)
857                 return false;
858         return cellInfo(cell).left_line;
859 }
860
861
862 bool Tabular::rightLine(idx_type cell) const
863 {
864         if (use_booktabs)
865                 return false;
866         return cellInfo(cell).right_line;
867 }
868
869
870 bool Tabular::topAlreadyDrawn(idx_type cell) const
871 {
872         row_type row = cellRow(cell);
873         if (row == 0)
874                 return false;
875         idx_type i = cellIndex(row - 1, cellColumn(cell));
876         return !rowTopLine(row) && bottomLine(i);
877 }
878
879
880 bool Tabular::leftAlreadyDrawn(idx_type cell) const
881 {
882         col_type col = cellColumn(cell);
883         if (col == 0)
884                 return false;
885         idx_type i = cellIndex(cellRow(cell), col - 1);
886         return rightLine(i) && !leftLine(cell);
887 }
888
889
890 bool Tabular::isLastRow(idx_type cell) const
891 {
892         return cellRow(cell) == row_info.size() - 1;
893 }
894
895
896 int Tabular::getAdditionalHeight(row_type row) const
897 {
898         if (!row || row >= row_info.size())
899                 return 0;
900
901         int const interline_space = row_info[row - 1].interline_space_default ?
902                 default_line_space :
903                 row_info[row - 1].interline_space.inPixels(width());
904         if (rowTopLine(row) && rowBottomLine(row - 1))
905                 return interline_space + WIDTH_OF_LINE;
906         return interline_space;
907 }
908
909
910 int Tabular::getAdditionalWidth(idx_type cell) const
911 {
912         col_type const nextcol = cellColumn(cell) + columnSpan(cell);
913         if (rightLine(cell) 
914                 && nextcol < column_info.size() && leftLine(cellIndex(cellRow(cell), nextcol)))
915                 return WIDTH_OF_LINE;
916         return 0;
917 }
918
919
920 int Tabular::columnWidth(idx_type cell) const
921 {
922         int w = 0;
923         col_type const span = columnSpan(cell);
924         col_type const col = cellColumn(cell);
925         for(col_type c = col; c < col + span ; ++c)
926                 w += column_info[c].width;
927         return w;
928 }
929
930
931 bool Tabular::updateColumnWidths()
932 {
933         col_type const ncols = column_info.size();
934         row_type const nrows = row_info.size();
935         bool update = false;
936         // for each col get max of single col cells
937         for(col_type c = 0; c < ncols; ++c) {
938                 int new_width = 0;
939                 for(row_type r = 0; r < nrows; ++r) {
940                         idx_type const i = cellIndex(r, c);
941                         if (columnSpan(i) == 1)
942                                 new_width = max(new_width, cellInfo(i).width);
943                 }
944
945                 if (column_info[c].width != new_width) {
946                         column_info[c].width = new_width;
947                         update = true;
948                 }
949         }
950         // update col widths to fit merged cells
951         for(col_type c = 0; c < ncols; ++c)
952                 for(row_type r = 0; r < nrows; ++r) {
953                         idx_type const i = cellIndex(r, c);
954                         int const span = columnSpan(i);
955                         if (span == 1 || c > cellColumn(i))
956                                 continue;
957
958                         int old_width = 0;
959                         for(col_type j = c; j < c + span ; ++j)
960                                 old_width += column_info[j].width;
961
962                         if (cellInfo(i).width > old_width) {
963                                 column_info[c + span - 1].width += cellInfo(i).width - old_width;
964                                 update = true;
965                         }
966                 }
967
968         return update;
969 }
970
971
972 int Tabular::width() const
973 {
974         col_type const ncols = column_info.size();
975         int width = 0;
976         for (col_type i = 0; i < ncols; ++i)
977                 width += column_info[i].width;
978         return width;
979 }
980
981
982 void Tabular::setCellWidth(idx_type cell, int new_width)
983 {
984         cellInfo(cell).width = new_width + 2 * WIDTH_OF_LINE 
985                 + getAdditionalWidth(cell);
986 }
987
988
989 void Tabular::setAlignment(idx_type cell, LyXAlignment align,
990                               bool onlycolumn)
991 {
992         if (!isMultiColumn(cell) || onlycolumn)
993                 column_info[cellColumn(cell)].alignment = align;
994         if (!onlycolumn)
995                 cellInfo(cell).alignment = align;
996         cellInset(cell).get()->setContentAlignment(align);
997 }
998
999
1000 void Tabular::setVAlignment(idx_type cell, VAlignment align,
1001                                bool onlycolumn)
1002 {
1003         if (!isMultiColumn(cell) || onlycolumn)
1004                 column_info[cellColumn(cell)].valignment = align;
1005         if (!onlycolumn)
1006                 cellInfo(cell).valignment = align;
1007 }
1008
1009
1010 namespace {
1011
1012 /**
1013  * Allow line and paragraph breaks for fixed width cells or disallow them,
1014  * merge cell paragraphs and reset layout to standard for variable width
1015  * cells.
1016  */
1017 void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
1018 {
1019         inset->setAutoBreakRows(fixedWidth);
1020         inset->toggleFixedWidth(fixedWidth);
1021         if (fixedWidth)
1022                 return;
1023
1024         // merge all paragraphs to one
1025         BufferParams const & bp = cur.bv().buffer().params();
1026         while (inset->paragraphs().size() > 1)
1027                 mergeParagraph(bp, inset->paragraphs(), 0);
1028
1029         // reset layout
1030         cur.push(*inset);
1031         // undo information has already been recorded
1032         inset->getText(0)->setLayout(cur.bv().buffer(), 0, cur.lastpit() + 1,
1033                         bp.documentClass().plainLayoutName());
1034         cur.pop();
1035 }
1036
1037 }
1038
1039
1040 void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
1041                 Length const & width)
1042 {
1043         col_type const j = cellColumn(cell);
1044
1045         column_info[j].p_width = width;
1046         for (row_type i = 0; i < row_info.size(); ++i) {
1047                 idx_type const cell = cellIndex(i, j);
1048                 // because of multicolumns
1049                 toggleFixedWidth(cur, cellInset(cell).get(),
1050                                  !getPWidth(cell).zero());
1051         }
1052         // cur paragraph can become invalid after paragraphs were merged
1053         if (cur.pit() > cur.lastpit())
1054                 cur.pit() = cur.lastpit();
1055         // cur position can become invalid after newlines were removed
1056         if (cur.pos() > cur.lastpos())
1057                 cur.pos() = cur.lastpos();
1058 }
1059
1060
1061 bool Tabular::setFixedWidth(row_type r, col_type c)
1062 {
1063         bool const multicol = cell_info[r][c].multicolumn != CELL_NORMAL;
1064         bool const fixed_width = (!column_info[c].p_width.zero() && !multicol)
1065               || (multicol && !cell_info[r][c].p_width.zero());
1066         cell_info[r][c].inset->toggleFixedWidth(fixed_width);
1067         return fixed_width;
1068 }
1069
1070
1071 void Tabular::updateContentAlignment(row_type r, col_type c)
1072 {
1073         cell_info[r][c].inset->setContentAlignment(
1074                 getAlignment(cellIndex(r, c)));
1075 }
1076
1077
1078 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
1079                 Length const & width)
1080 {
1081         if (!isMultiColumn(cell))
1082                 return false;
1083
1084         cellInfo(cell).p_width = width;
1085         toggleFixedWidth(cur, cellInset(cell).get(), !width.zero());
1086         // cur paragraph can become invalid after paragraphs were merged
1087         if (cur.pit() > cur.lastpit())
1088                 cur.pit() = cur.lastpit();
1089         // cur position can become invalid after newlines were removed
1090         if (cur.pos() > cur.lastpos())
1091                 cur.pos() = cur.lastpos();
1092         return true;
1093 }
1094
1095
1096 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
1097                                  Tabular::Feature what)
1098 {
1099         if (what == SET_SPECIAL_MULTI)
1100                 cellInfo(cell).align_special = special;
1101         else
1102                 column_info[cellColumn(cell)].align_special = special;
1103 }
1104
1105
1106 void Tabular::setAllLines(idx_type cell, bool line)
1107 {
1108         setTopLine(cell, line);
1109         setBottomLine(cell, line);
1110         setRightLine(cell, line);
1111         setLeftLine(cell, line);
1112 }
1113
1114
1115 void Tabular::setTopLine(idx_type i, bool line)
1116 {
1117         cellInfo(i).top_line = line;
1118 }
1119
1120
1121 void Tabular::setBottomLine(idx_type i, bool line)
1122 {
1123         cellInfo(i).bottom_line = line;
1124 }
1125
1126
1127 void Tabular::setLeftLine(idx_type cell, bool line)
1128 {
1129         cellInfo(cell).left_line = line;
1130 }
1131
1132
1133 void Tabular::setRightLine(idx_type cell, bool line)
1134 {
1135         cellInfo(cell).right_line = line;
1136 }
1137
1138 bool Tabular::rowTopLine(row_type r) const
1139 {
1140         idx_type i0 = getFirstCellInRow(r);
1141         idx_type i1 = getLastCellInRow(r);
1142         bool all_rows_set = true;
1143         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1144                 all_rows_set = cellInfo(j).top_line;
1145         return all_rows_set;
1146 }
1147
1148
1149 bool Tabular::rowBottomLine(row_type r) const
1150 {
1151         idx_type i0 = getFirstCellInRow(r);
1152         idx_type i1 = getLastCellInRow(r);
1153         bool all_rows_set = true;
1154         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1155                 all_rows_set = cellInfo(j).bottom_line;
1156         return all_rows_set;
1157 }
1158
1159
1160 bool Tabular::columnLeftLine(col_type c) const
1161 {
1162         if (use_booktabs)
1163                 return false;
1164
1165         int nrows_left = 0;
1166         int total = 0;
1167         row_type const nrows = row_info.size();
1168         for (row_type r = 0; r < nrows; ++r) {
1169                 idx_type i = cellIndex(r, c);
1170                 if (c == cellColumn(i)) {
1171                         ++total;
1172                         bool right = c > 0 && cellInfo(cellIndex(r, c - 1)).right_line;
1173                         if (cellInfo(i).left_line || right)
1174                                 ++nrows_left;
1175                 }
1176         }
1177         return 2 * nrows_left >= total;
1178 }
1179
1180
1181 bool Tabular::columnRightLine(col_type c) const
1182 {
1183         if (use_booktabs)
1184                 return false;
1185
1186         int nrows_right = 0;
1187         int total = 0;
1188         row_type const nrows = row_info.size();
1189         for (row_type r = 0; r < nrows; ++r) {
1190                 idx_type i = cellIndex(r, c);
1191                 if (c == cellColumn(i) + columnSpan(i) - 1) {
1192                         ++total;
1193                         bool left = (c + 1 < column_info.size() 
1194                                 && cellInfo(cellIndex(r, c + 1)).left_line)
1195                                 || c + 1 == column_info.size();
1196                         if (cellInfo(i).right_line && left)
1197                                 ++nrows_right;
1198                 }
1199         }
1200         return 2 * nrows_right >= total;
1201 }
1202
1203
1204 LyXAlignment Tabular::getAlignment(idx_type cell, bool onlycolumn) const
1205 {
1206         if (!onlycolumn && isMultiColumn(cell))
1207                 return cellInfo(cell).alignment;
1208         return column_info[cellColumn(cell)].alignment;
1209 }
1210
1211
1212 Tabular::VAlignment
1213 Tabular::getVAlignment(idx_type cell, bool onlycolumn) const
1214 {
1215         if (!onlycolumn && isMultiColumn(cell))
1216                 return cellInfo(cell).valignment;
1217         return column_info[cellColumn(cell)].valignment;
1218 }
1219
1220
1221 Length const Tabular::getPWidth(idx_type cell) const
1222 {
1223         if (isMultiColumn(cell))
1224                 return cellInfo(cell).p_width;
1225         return column_info[cellColumn(cell)].p_width;
1226 }
1227
1228
1229 int Tabular::cellWidth(idx_type cell) const
1230 {
1231         return cellInfo(cell).width;
1232 }
1233
1234
1235 int Tabular::getBeginningOfTextInCell(idx_type cell) const
1236 {
1237         int x = 0;
1238
1239         switch (getAlignment(cell)) {
1240         case LYX_ALIGN_CENTER:
1241                 x += (columnWidth(cell) - cellWidth(cell)) / 2;
1242                 break;
1243         case LYX_ALIGN_RIGHT:
1244                 x += columnWidth(cell) - cellWidth(cell);
1245                 // + getAdditionalWidth(cell);
1246                 break;
1247         default:
1248                 // LYX_ALIGN_LEFT: nothing :-)
1249                 break;
1250         }
1251
1252         // the LaTeX Way :-(
1253         x += WIDTH_OF_LINE;
1254         return x;
1255 }
1256
1257
1258 bool Tabular::isFirstCellInRow(idx_type cell) const
1259 {
1260         return cellColumn(cell) == 0;
1261 }
1262
1263
1264 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
1265 {
1266         if (row > row_info.size() - 1)
1267                 row = row_info.size() - 1;
1268         return cell_info[row][0].cellno;
1269 }
1270
1271
1272 bool Tabular::isLastCellInRow(idx_type cell) const
1273 {
1274         return cellRightColumn(cell) == column_info.size() - 1;
1275 }
1276
1277
1278 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
1279 {
1280         if (row > row_info.size() - 1)
1281                 row = row_info.size() - 1;
1282         return cell_info[row][column_info.size() - 1].cellno;
1283 }
1284
1285
1286 Tabular::row_type Tabular::cellRow(idx_type cell) const
1287 {
1288         if (cell >= numberofcells)
1289                 return row_info.size() - 1;
1290         if (cell == npos)
1291                 return 0;
1292         return rowofcell[cell];
1293 }
1294
1295
1296 Tabular::col_type Tabular::cellColumn(idx_type cell) const
1297 {
1298         if (cell >= numberofcells)
1299                 return column_info.size() - 1;
1300         if (cell == npos)
1301                 return 0;       
1302         return columnofcell[cell];
1303 }
1304
1305
1306 Tabular::col_type Tabular::cellRightColumn(idx_type cell) const
1307 {
1308         row_type const row = cellRow(cell);
1309         col_type column = cellColumn(cell);
1310         while (column < column_info.size() - 1 &&
1311                    cell_info[row][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN)
1312                 ++column;
1313         return column;
1314 }
1315
1316
1317 void Tabular::write(ostream & os) const
1318 {
1319         // header line
1320         os << "<lyxtabular"
1321            << write_attribute("version", 3)
1322            << write_attribute("rows", row_info.size())
1323            << write_attribute("columns", column_info.size())
1324            << ">\n";
1325         // global longtable options
1326         os << "<features"
1327            << write_attribute("rotate", rotate)
1328            << write_attribute("booktabs", use_booktabs)
1329            << write_attribute("islongtable", is_long_tabular);
1330         // longtables cannot be aligned vertically
1331         if (!is_long_tabular)
1332            os << write_attribute("tabularvalignment", tabular_valignment);
1333         if (is_long_tabular)
1334            os << write_attribute("longtabularalignment",
1335                                                          longtabular_alignment);
1336         os << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1337            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1338            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1339            << write_attribute("headTopDL", endhead.topDL)
1340            << write_attribute("headBottomDL", endhead.bottomDL)
1341            << write_attribute("footTopDL", endfoot.topDL)
1342            << write_attribute("footBottomDL", endfoot.bottomDL)
1343            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1344            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1345            << write_attribute("lastFootEmpty", endlastfoot.empty)
1346            << ">\n";
1347         for (col_type j = 0; j < column_info.size(); ++j) {
1348                 os << "<column"
1349                    << write_attribute("alignment", column_info[j].alignment)
1350                    << write_attribute("valignment", column_info[j].valignment)
1351                    << write_attribute("width", column_info[j].p_width.asString())
1352                    << write_attribute("special", column_info[j].align_special)
1353                    << ">\n";
1354         }
1355         for (row_type i = 0; i < row_info.size(); ++i) {
1356                 static const string def("default");
1357                 os << "<row";
1358                 if (row_info[i].top_space_default)
1359                         os << write_attribute("topspace", def);
1360                 else
1361                         os << write_attribute("topspace", row_info[i].top_space);
1362                 if (row_info[i].bottom_space_default)
1363                         os << write_attribute("bottomspace", def);
1364                 else
1365                         os << write_attribute("bottomspace", row_info[i].bottom_space);
1366                 if (row_info[i].interline_space_default)
1367                         os << write_attribute("interlinespace", def);
1368                 else
1369                         os << write_attribute("interlinespace", row_info[i].interline_space);
1370                 os << write_attribute("endhead", row_info[i].endhead)
1371                    << write_attribute("endfirsthead", row_info[i].endfirsthead)
1372                    << write_attribute("endfoot", row_info[i].endfoot)
1373                    << write_attribute("endlastfoot", row_info[i].endlastfoot)
1374                    << write_attribute("newpage", row_info[i].newpage)
1375                    << write_attribute("caption", row_info[i].caption)
1376                    << ">\n";
1377                 for (col_type j = 0; j < column_info.size(); ++j) {
1378                         os << "<cell"
1379                            << write_attribute("multicolumn", cell_info[i][j].multicolumn)
1380                            << write_attribute("alignment", cell_info[i][j].alignment)
1381                            << write_attribute("valignment", cell_info[i][j].valignment)
1382                            << write_attribute("topline", cell_info[i][j].top_line)
1383                            << write_attribute("bottomline", cell_info[i][j].bottom_line)
1384                            << write_attribute("leftline", cell_info[i][j].left_line)
1385                            << write_attribute("rightline", cell_info[i][j].right_line)
1386                            << write_attribute("rotate", cell_info[i][j].rotate)
1387                            << write_attribute("usebox", cell_info[i][j].usebox)
1388                            << write_attribute("width", cell_info[i][j].p_width)
1389                            << write_attribute("special", cell_info[i][j].align_special)
1390                            << ">\n";
1391                         os << "\\begin_inset ";
1392                         cell_info[i][j].inset->write(os);
1393                         os << "\n\\end_inset\n"
1394                            << "</cell>\n";
1395                 }
1396                 os << "</row>\n";
1397         }
1398         os << "</lyxtabular>\n";
1399 }
1400
1401
1402 void Tabular::read(Lexer & lex)
1403 {
1404         string line;
1405         istream & is = lex.getStream();
1406
1407         l_getline(is, line);
1408         if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
1409                 LASSERT(false, /**/);
1410                 return;
1411         }
1412
1413         int version;
1414         if (!getTokenValue(line, "version", version))
1415                 return;
1416         LASSERT(version >= 2, /**/);
1417
1418         int rows_arg;
1419         if (!getTokenValue(line, "rows", rows_arg))
1420                 return;
1421         int columns_arg;
1422         if (!getTokenValue(line, "columns", columns_arg))
1423                 return;
1424         init(buffer(), rows_arg, columns_arg);
1425         l_getline(is, line);
1426         if (!prefixIs(line, "<features")) {
1427                 lyxerr << "Wrong tabular format (expected <features ...> got"
1428                        << line << ')' << endl;
1429                 return;
1430         }
1431         getTokenValue(line, "rotate", rotate);
1432         getTokenValue(line, "booktabs", use_booktabs);
1433         getTokenValue(line, "islongtable", is_long_tabular);
1434         getTokenValue(line, "tabularvalignment", tabular_valignment);
1435         getTokenValue(line, "longtabularalignment", longtabular_alignment);
1436         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1437         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1438         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1439         getTokenValue(line, "headTopDL", endhead.topDL);
1440         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1441         getTokenValue(line, "footTopDL", endfoot.topDL);
1442         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1443         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1444         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1445         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1446
1447         for (col_type j = 0; j < column_info.size(); ++j) {
1448                 l_getline(is,line);
1449                 if (!prefixIs(line,"<column")) {
1450                         lyxerr << "Wrong tabular format (expected <column ...> got"
1451                                << line << ')' << endl;
1452                         return;
1453                 }
1454                 getTokenValue(line, "alignment", column_info[j].alignment);
1455                 getTokenValue(line, "valignment", column_info[j].valignment);
1456                 getTokenValue(line, "width", column_info[j].p_width);
1457                 getTokenValue(line, "special", column_info[j].align_special);
1458         }
1459
1460         for (row_type i = 0; i < row_info.size(); ++i) {
1461                 l_getline(is, line);
1462                 if (!prefixIs(line, "<row")) {
1463                         lyxerr << "Wrong tabular format (expected <row ...> got"
1464                                << line << ')' << endl;
1465                         return;
1466                 }
1467                 getTokenValue(line, "topspace", row_info[i].top_space,
1468                               row_info[i].top_space_default);
1469                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1470                               row_info[i].bottom_space_default);
1471                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1472                               row_info[i].interline_space_default);
1473                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1474                 getTokenValue(line, "endhead", row_info[i].endhead);
1475                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1476                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1477                 getTokenValue(line, "newpage", row_info[i].newpage);
1478                 getTokenValue(line, "caption", row_info[i].caption);
1479                 for (col_type j = 0; j < column_info.size(); ++j) {
1480                         l_getline(is, line);
1481                         if (!prefixIs(line, "<cell")) {
1482                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1483                                        << line << ')' << endl;
1484                                 return;
1485                         }
1486                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1487                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1488                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1489                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1490                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1491                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1492                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1493                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1494                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1495                         getTokenValue(line, "width", cell_info[i][j].p_width);
1496                         setFixedWidth(i,j);
1497                         getTokenValue(line, "special", cell_info[i][j].align_special);
1498                         l_getline(is, line);
1499                         if (prefixIs(line, "\\begin_inset")) {
1500                                 cell_info[i][j].inset->setBuffer(*buffer_);
1501                                 cell_info[i][j].inset->read(lex);
1502                                 l_getline(is, line);
1503                         }
1504                         if (!prefixIs(line, "</cell>")) {
1505                                 lyxerr << "Wrong tabular format (expected </cell> got"
1506                                        << line << ')' << endl;
1507                                 return;
1508                         }
1509                 }
1510                 l_getline(is, line);
1511                 if (!prefixIs(line, "</row>")) {
1512                         lyxerr << "Wrong tabular format (expected </row> got"
1513                                << line << ')' << endl;
1514                         return;
1515                 }
1516         }
1517         while (!prefixIs(line, "</lyxtabular>")) {
1518                 l_getline(is, line);
1519         }
1520         updateIndexes();
1521 }
1522
1523
1524 bool Tabular::isMultiColumn(idx_type cell) const
1525 {
1526         return cellInfo(cell).multicolumn != CELL_NORMAL;
1527 }
1528
1529
1530 bool Tabular::isMultiColumnReal(idx_type cell) const
1531 {
1532         return cellColumn(cell) != cellRightColumn(cell) &&
1533                         cellInfo(cell).multicolumn != CELL_NORMAL;
1534 }
1535
1536
1537 Tabular::CellData & Tabular::cellInfo(idx_type cell) const
1538 {
1539         return cell_info[cellRow(cell)][cellColumn(cell)];
1540 }
1541
1542
1543 void Tabular::setMultiColumn(idx_type cell, idx_type number)
1544 {
1545         CellData & cs = cellInfo(cell);
1546         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1547         cs.alignment = column_info[cellColumn(cell)].alignment;
1548         setRightLine(cell, rightLine(cell + number - 1));
1549         for (idx_type i = 1; i < number; ++i) {
1550                 CellData & cs1 = cellInfo(cell + i);
1551                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1552                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1553                 cs1.inset->clear();
1554         }
1555         updateIndexes();
1556 }
1557
1558
1559 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
1560 {
1561         row_type const row = cellRow(cell);
1562         col_type const ncols = column_info.size();
1563         idx_type result = 1;
1564         col_type column = cellColumn(cell) + 1;
1565         while (column < ncols && isPartOfMultiColumn(row, column)) {
1566                 ++result;
1567                 ++column;
1568         }
1569         return result;
1570 }
1571
1572
1573 Tabular::idx_type Tabular::unsetMultiColumn(idx_type cell)
1574 {
1575         row_type const row = cellRow(cell);
1576         col_type column = cellColumn(cell);
1577
1578         idx_type result = 0;
1579
1580         if (cell_info[row][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN) {
1581                 cell_info[row][column].multicolumn = CELL_NORMAL;
1582                 ++column;
1583                 while (column < column_info.size() &&
1584                            cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
1585                 {
1586                         cell_info[row][column].multicolumn = CELL_NORMAL;
1587                         ++column;
1588                         ++result;
1589                 }
1590         }
1591         updateIndexes();
1592         return result;
1593 }
1594
1595
1596 void Tabular::setRotateCell(idx_type cell, bool flag)
1597 {
1598         cellInfo(cell).rotate = flag;
1599 }
1600
1601
1602 bool Tabular::getRotateCell(idx_type cell) const
1603 {
1604         return cellInfo(cell).rotate;
1605 }
1606
1607
1608 bool Tabular::needRotating() const
1609 {
1610         if (rotate)
1611                 return true;
1612         for (row_type i = 0; i < row_info.size(); ++i)
1613                 for (col_type j = 0; j < column_info.size(); ++j)
1614                         if (cell_info[i][j].rotate)
1615                                 return true;
1616         return false;
1617 }
1618
1619
1620 bool Tabular::isLastCell(idx_type cell) const
1621 {
1622         if (cell + 1 < numberofcells)
1623                 return false;
1624         return true;
1625 }
1626
1627
1628 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
1629 {
1630         if (cellRow(cell) > 0)
1631                 return cell_info[cellRow(cell)-1][cellColumn(cell)].cellno;
1632         return cell;
1633 }
1634
1635
1636 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
1637 {
1638         if (cellRow(cell) + 1 < row_info.size())
1639                 return cell_info[cellRow(cell)+1][cellColumn(cell)].cellno;
1640         return cell;
1641 }
1642
1643
1644 Tabular::idx_type Tabular::cellIndex(row_type row,
1645                                                col_type column) const
1646 {
1647         BOOST_ASSERT(column != npos && column < column_info.size()
1648                 && row != npos && row < row_info.size());
1649         return cell_info[row][column].cellno;
1650 }
1651
1652
1653 void Tabular::setUsebox(idx_type cell, BoxType type)
1654 {
1655         cellInfo(cell).usebox = type;
1656 }
1657
1658
1659 // FIXME: Remove this routine because we cannot insert \parboxes when the user
1660 // adds line breaks, see bug 4886.
1661 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
1662 {
1663         if ((!column_info[cellColumn(cell)].p_width.zero() && !isMultiColumn(cell)) ||
1664                 (isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
1665                 return BOX_NONE;
1666         if (cellInfo(cell).usebox > 1)
1667                 return cellInfo(cell).usebox;
1668         return useParbox(cell);
1669 }
1670
1671
1672 ///
1673 //  This are functions used for the longtable support
1674 ///
1675 void Tabular::setLTHead(row_type row, bool flag, ltType const & hd,
1676                            bool first)
1677 {
1678         if (first) {
1679                 endfirsthead = hd;
1680                 if (hd.set)
1681                         row_info[row].endfirsthead = flag;
1682         } else {
1683                 endhead = hd;
1684                 if (hd.set)
1685                         row_info[row].endhead = flag;
1686         }
1687 }
1688
1689
1690 bool Tabular::getRowOfLTHead(row_type row, ltType & hd) const
1691 {
1692         hd = endhead;
1693         hd.set = haveLTHead();
1694         return row_info[row].endhead;
1695 }
1696
1697
1698 bool Tabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1699 {
1700         hd = endfirsthead;
1701         hd.set = haveLTFirstHead();
1702         return row_info[row].endfirsthead;
1703 }
1704
1705
1706 void Tabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1707                            bool last)
1708 {
1709         if (last) {
1710                 endlastfoot = fd;
1711                 if (fd.set)
1712                         row_info[row].endlastfoot = flag;
1713         } else {
1714                 endfoot = fd;
1715                 if (fd.set)
1716                         row_info[row].endfoot = flag;
1717         }
1718 }
1719
1720
1721 bool Tabular::getRowOfLTFoot(row_type row, ltType & fd) const
1722 {
1723         fd = endfoot;
1724         fd.set = haveLTFoot();
1725         return row_info[row].endfoot;
1726 }
1727
1728
1729 bool Tabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1730 {
1731         fd = endlastfoot;
1732         fd.set = haveLTLastFoot();
1733         return row_info[row].endlastfoot;
1734 }
1735
1736
1737 void Tabular::setLTNewPage(row_type row, bool what)
1738 {
1739         row_info[row].newpage = what;
1740 }
1741
1742
1743 bool Tabular::getLTNewPage(row_type row) const
1744 {
1745         return row_info[row].newpage;
1746 }
1747
1748
1749 bool Tabular::haveLTHead() const
1750 {
1751         for (row_type i = 0; i < row_info.size(); ++i)
1752                 if (row_info[i].endhead)
1753                         return true;
1754         return false;
1755 }
1756
1757
1758 bool Tabular::haveLTFirstHead() const
1759 {
1760         if (endfirsthead.empty)
1761                 return false;
1762         for (row_type i = 0; i < row_info.size(); ++i)
1763                 if (row_info[i].endfirsthead)
1764                         return true;
1765         return false;
1766 }
1767
1768
1769 bool Tabular::haveLTFoot() const
1770 {
1771         for (row_type i = 0; i < row_info.size(); ++i)
1772                 if (row_info[i].endfoot)
1773                         return true;
1774         return false;
1775 }
1776
1777
1778 bool Tabular::haveLTLastFoot() const
1779 {
1780         if (endlastfoot.empty)
1781                 return false;
1782         for (row_type i = 0; i < row_info.size(); ++i)
1783                 if (row_info[i].endlastfoot)
1784                         return true;
1785         return false;
1786 }
1787
1788
1789 Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
1790 {
1791         idx_type i = getFirstCellInRow(row);
1792         if (what) {
1793                 setMultiColumn(i, numberOfCellsInRow(i));
1794                 setTopLine(i, false);
1795                 setBottomLine(i, false);
1796                 setLeftLine(i, false);
1797                 setRightLine(i, false);
1798         } else {
1799                 unsetMultiColumn(i);
1800                 // FIXME: when unsetting a caption row, also all existing captions
1801                 // in this row must be dissolved, see (bug 5754)
1802                 // dispatch(FuncRequest(LFUN_INSET_DISSOLVE, "caption-insert"));
1803         }
1804         row_info[row].caption = what;
1805         return i;
1806 }
1807
1808
1809 bool Tabular::ltCaption(row_type row) const
1810 {
1811         return row_info[row].caption;
1812 }
1813
1814
1815 bool Tabular::haveLTCaption() const
1816 {
1817         for (row_type i = 0; i < row_info.size(); ++i)
1818                 if (row_info[i].caption)
1819                         return true;
1820         return false;
1821 }
1822
1823
1824 // end longtable support functions
1825
1826 void Tabular::setRowAscent(row_type row, int height)
1827 {
1828         if (row >= row_info.size() || row_info[row].ascent == height)
1829                 return;
1830         row_info[row].ascent = height;
1831 }
1832
1833
1834 void Tabular::setRowDescent(row_type row, int height)
1835 {
1836         if (row >= row_info.size() || row_info[row].descent == height)
1837                 return;
1838         row_info[row].descent = height;
1839 }
1840
1841
1842 int Tabular::rowAscent(row_type row) const
1843 {
1844         if (row >= row_info.size())
1845                 return 0;
1846         return row_info[row].ascent;
1847 }
1848
1849
1850 int Tabular::rowDescent(row_type row) const
1851 {
1852         LASSERT(row < row_info.size(), /**/);
1853         return row_info[row].descent;
1854 }
1855
1856
1857 int Tabular::height() const
1858 {
1859         int height = 0;
1860         for (row_type row = 0; row < row_info.size(); ++row)
1861                 height += rowAscent(row) + rowDescent(row) +
1862                         getAdditionalHeight(row);
1863         return height;
1864 }
1865
1866
1867 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
1868 {
1869         LASSERT(row < row_info.size(), /**/);
1870         LASSERT(column < column_info.size(), /**/);
1871         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
1872 }
1873
1874
1875 int Tabular::TeXTopHLine(odocstream & os, row_type row, string const lang) const
1876 {
1877         // we only output complete row lines and the 1st row here, the rest
1878         // is done in Tabular::TeXBottomHLine(...)
1879
1880         // get for each column the topline (if any)
1881         col_type const ncols = column_info.size();
1882         vector<bool> topline;
1883         col_type nset = 0;
1884         for (col_type c = 0; c < ncols; ++c) {
1885                 topline.push_back(topLine(cellIndex(row, c)));
1886                 if (topline[c])
1887                         ++nset;
1888         }
1889
1890         // do nothing if empty first row, or incomplete row line after
1891         if ((row == 0 && nset == 0) || (row > 0 && nset != ncols))
1892                 return 0;
1893
1894         // only output complete row lines and the 1st row's clines
1895         if (nset == ncols) {
1896                 if (use_booktabs) {
1897                         os << (row == 0 ? "\\toprule " : "\\midrule ");
1898                 } else {
1899                         os << "\\hline ";
1900                 }
1901         } else if (row == 0) {
1902                 for (col_type c = 0; c < ncols; ++c) {
1903                         if (topline[c]) {
1904                                 //babel makes the "-" character an active one, so we have to suppress this here
1905                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
1906                                 if (lang == "slovak" || lang == "czech")
1907                                         os << (use_booktabs ? "\\expandafter\\cmidrule\\expandafter{\\expandafter" :
1908                                                               "\\expandafter\\cline\\expandafter{\\expandafter")
1909                                                                                   << c + 1 << "\\string-";
1910                                 else
1911                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 << '-';
1912                                 // get to last column of line span
1913                                 while (c < ncols && topline[c])
1914                                         ++c;
1915                                 os << c << "} ";
1916                         }
1917                 }
1918         }
1919         os << "\n";
1920         return 1;
1921 }
1922
1923
1924 int Tabular::TeXBottomHLine(odocstream & os, row_type row, string const lang) const
1925 {
1926         // we output bottomlines of row r and the toplines of row r+1
1927         // if the latter do not span the whole tabular
1928
1929         // get the bottomlines of row r, and toplines in next row
1930         bool lastrow = row == row_info.size() - 1;
1931         col_type const ncols = column_info.size();
1932         vector<bool> bottomline, topline;
1933         bool nextrowset = true;
1934         for (col_type c = 0; c < ncols; ++c) {
1935                 bottomline.push_back(bottomLine(cellIndex(row, c)));
1936                 topline.push_back(!lastrow && topLine(cellIndex(row + 1, c)));
1937                 nextrowset &= topline[c];
1938         }
1939
1940         // combine this row's bottom lines and next row's toplines if necessary
1941         col_type nset = 0;
1942         for (col_type c = 0; c < ncols; ++c) {
1943                 if (!nextrowset)
1944                         bottomline[c] = bottomline[c] || topline[c];
1945                 if (bottomline[c])
1946                         ++nset;
1947         }
1948
1949         // do nothing if empty, OR incomplete row line with a topline in next row
1950         if (nset == 0 || (nextrowset && nset != ncols))
1951                 return 0;
1952
1953         if (nset == ncols) {
1954                 if (use_booktabs)
1955                         os << (lastrow ? "\\bottomrule" : "\\midrule");
1956                 else
1957                         os << "\\hline";
1958         } else {
1959                 for (col_type c = 0; c < ncols; ++c) {
1960                         if (bottomline[c]) {
1961                                 //babel makes the "-" character an active one, so we have to suppress this here
1962                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
1963                                 if (lang == "slovak" || lang == "czech")
1964                                         os << (use_booktabs ? "\\expandafter\\cmidrule\\expandafter{\\expandafter" :
1965                                                               "\\expandafter\\cline\\expandafter{\\expandafter")
1966                                                                                   << c + 1 << "\\string-";
1967                                 else
1968                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 << '-';
1969                                 // get to last column of line span
1970                                 while (c < ncols && bottomline[c])
1971                                         ++c;
1972                                 os << c << "} ";
1973                         }
1974                 }
1975         }
1976         os << "\n";
1977         return 1;
1978 }
1979
1980
1981 int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol) const
1982 {
1983         int ret = 0;
1984         row_type const r = cellRow(cell);
1985         if (is_long_tabular && row_info[r].caption)
1986                 return ret;
1987
1988         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
1989         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
1990         // figure out how to set the lines
1991         // we always set double lines to the right of the cell
1992         col_type const c = cellColumn(cell);
1993         col_type const nextcol = c + columnSpan(cell);
1994         bool colright = columnRightLine(c);
1995         bool colleft = columnLeftLine(c);
1996         bool nextcolleft = nextcol < column_info.size() && columnLeftLine(nextcol);
1997         bool nextcellleft = nextcol < column_info.size() 
1998                 && leftLine(cellIndex(r, nextcol));
1999         bool coldouble = colright && nextcolleft;
2000         bool celldouble = rightLine(cell) && nextcellleft;
2001         ismulticol = isMultiColumn(cell) 
2002                 || (c == 0 && colleft != leftLine(cell))
2003                 || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
2004                 || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
2005                 || (coldouble != celldouble);
2006         if (ismulticol) {
2007                 os << "\\multicolumn{" << columnSpan(cell) << "}{";
2008                 if (c ==0 && leftLine(cell))
2009                         os << '|';
2010                 if (!cellInfo(cell).align_special.empty()) {
2011                         os << cellInfo(cell).align_special;
2012                 } else {
2013                         if (!getPWidth(cell).zero()) {
2014                                 switch (align) {
2015                                 case LYX_ALIGN_LEFT:
2016                                         os << ">{\\raggedright}";
2017                                         break;
2018                                 case LYX_ALIGN_RIGHT:
2019                                         os << ">{\\raggedleft}";
2020                                         break;
2021                                 case LYX_ALIGN_CENTER:
2022                                         os << ">{\\centering}";
2023                                         break;
2024                                 default:
2025                                         break;
2026                                 }
2027                                 switch (valign) {
2028                                 case LYX_VALIGN_TOP:
2029                                         os << 'p';
2030                                         break;
2031                                 case LYX_VALIGN_MIDDLE:
2032                                         os << 'm';
2033                                         break;
2034                                 case LYX_VALIGN_BOTTOM:
2035                                         os << 'b';
2036                                         break;
2037                                 }
2038                                 os << '{'
2039                                    << from_ascii(getPWidth(cell).asLatexString())
2040                                    << '}';
2041                         } else {
2042                                 switch (align) {
2043                                 case LYX_ALIGN_LEFT:
2044                                         os << 'l';
2045                                         break;
2046                                 case LYX_ALIGN_RIGHT:
2047                                         os << 'r';
2048                                         break;
2049                                 default:
2050                                         os << 'c';
2051                                         break;
2052                                 }
2053                         } // end if else !getPWidth
2054                 } // end if else !cellinfo_of_cell
2055                 if (rightLine(cell) || nextcellleft)
2056                         os << '|';
2057                 if (celldouble)
2058                         // add extra vertical line if we want a double one
2059                         os << '|';
2060                 os << "}{";
2061                 }
2062         if (getRotateCell(cell)) {
2063                 os << "\\begin{sideways}\n";
2064                 ++ret;
2065         }
2066         if (getUsebox(cell) == BOX_PARBOX) {
2067                 os << "\\parbox[";
2068                 switch (valign) {
2069                 case LYX_VALIGN_TOP:
2070                         os << 't';
2071                         break;
2072                 case LYX_VALIGN_MIDDLE:
2073                         os << 'c';
2074                         break;
2075                 case LYX_VALIGN_BOTTOM:
2076                         os << 'b';
2077                         break;
2078                 }
2079                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2080                    << "}{";
2081         } else if (getUsebox(cell) == BOX_MINIPAGE) {
2082                 os << "\\begin{minipage}[";
2083                 switch (valign) {
2084                 case LYX_VALIGN_TOP:
2085                         os << 't';
2086                         break;
2087                 case LYX_VALIGN_MIDDLE:
2088                         os << 'm';
2089                         break;
2090                 case LYX_VALIGN_BOTTOM:
2091                         os << 'b';
2092                         break;
2093                 }
2094                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2095                    << "}\n";
2096                 ++ret;
2097         }
2098         return ret;
2099 }
2100
2101
2102 int Tabular::TeXCellPostamble(odocstream & os, idx_type cell, bool ismulticol) const
2103 {
2104         int ret = 0;
2105         row_type const r = cellRow(cell);
2106         if (is_long_tabular && row_info[r].caption)
2107                 return ret;
2108
2109         // usual cells
2110         if (getUsebox(cell) == BOX_PARBOX)
2111                 os << '}';
2112         else if (getUsebox(cell) == BOX_MINIPAGE) {
2113                 os << "%\n\\end{minipage}";
2114                 ret += 2;
2115         }
2116         if (getRotateCell(cell)) {
2117                 os << "%\n\\end{sideways}";
2118                 ++ret;
2119         }
2120         if (ismulticol) {
2121                 os << '}';
2122         }
2123         return ret;
2124 }
2125
2126
2127 int Tabular::TeXLongtableHeaderFooter(odocstream & os,
2128                                          OutputParams const & runparams) const
2129 {
2130         if (!is_long_tabular)
2131                 return 0;
2132
2133         int ret = 0;
2134         // caption handling
2135         // the caption must be output befrore the headers
2136         if (haveLTCaption()) {
2137                 for (row_type i = 0; i < row_info.size(); ++i) {
2138                         if (row_info[i].caption) {
2139                                 ret += TeXRow(os, i, runparams);
2140                         }
2141                 }
2142         }
2143         // output first header info
2144         // first header must be output before the header, otherwise the
2145         // correct caption placement becomes really weird
2146         if (haveLTFirstHead()) {
2147                 if (endfirsthead.topDL) {
2148                         os << "\\hline\n";
2149                         ++ret;
2150                 }
2151                 for (row_type i = 0; i < row_info.size(); ++i) {
2152                         if (row_info[i].endfirsthead) {
2153                                 ret += TeXRow(os, i, runparams);
2154                         }
2155                 }
2156                 if (endfirsthead.bottomDL) {
2157                         os << "\\hline\n";
2158                         ++ret;
2159                 }
2160                 os << "\\endfirsthead\n";
2161                 ++ret;
2162         }
2163         // output header info
2164         if (haveLTHead()) {
2165                 if (endfirsthead.empty && !haveLTFirstHead()) {
2166                         os << "\\endfirsthead\n";
2167                         ++ret;
2168                 }
2169                 if (endhead.topDL) {
2170                         os << "\\hline\n";
2171                         ++ret;
2172                 }
2173                 for (row_type i = 0; i < row_info.size(); ++i) {
2174                         if (row_info[i].endhead) {
2175                                 ret += TeXRow(os, i, runparams);
2176                         }
2177                 }
2178                 if (endhead.bottomDL) {
2179                         os << "\\hline\n";
2180                         ++ret;
2181                 }
2182                 os << "\\endhead\n";
2183                 ++ret;
2184         }
2185         // output footer info
2186         if (haveLTFoot()) {
2187                 if (endfoot.topDL) {
2188                         os << "\\hline\n";
2189                         ++ret;
2190                 }
2191                 for (row_type i = 0; i < row_info.size(); ++i) {
2192                         if (row_info[i].endfoot) {
2193                                 ret += TeXRow(os, i, runparams);
2194                         }
2195                 }
2196                 if (endfoot.bottomDL) {
2197                         os << "\\hline\n";
2198                         ++ret;
2199                 }
2200                 os << "\\endfoot\n";
2201                 ++ret;
2202                 if (endlastfoot.empty && !haveLTLastFoot()) {
2203                         os << "\\endlastfoot\n";
2204                         ++ret;
2205                 }
2206         }
2207         // output lastfooter info
2208         if (haveLTLastFoot()) {
2209                 if (endlastfoot.topDL) {
2210                         os << "\\hline\n";
2211                         ++ret;
2212                 }
2213                 for (row_type i = 0; i < row_info.size(); ++i) {
2214                         if (row_info[i].endlastfoot) {
2215                                 ret += TeXRow(os, i, runparams);
2216                         }
2217                 }
2218                 if (endlastfoot.bottomDL) {
2219                         os << "\\hline\n";
2220                         ++ret;
2221                 }
2222                 os << "\\endlastfoot\n";
2223                 ++ret;
2224         }
2225         return ret;
2226 }
2227
2228
2229 bool Tabular::isValidRow(row_type row) const
2230 {
2231         if (!is_long_tabular)
2232                 return true;
2233         return !row_info[row].endhead && !row_info[row].endfirsthead
2234                 && !row_info[row].endfoot && !row_info[row].endlastfoot
2235                 && !row_info[row].caption;
2236 }
2237
2238
2239 int Tabular::TeXRow(odocstream & os, row_type i,
2240                        OutputParams const & runparams) const
2241 {
2242         idx_type cell = cellIndex(i, 0);
2243         shared_ptr<InsetTableCell> inset = cellInset(cell);
2244         Paragraph const & par = inset->paragraphs().front();
2245         string const lang = par.getParLanguage(buffer().params())->lang();
2246
2247         //output the top line
2248         int ret = TeXTopHLine(os, i, lang);
2249
2250         if (row_info[i].top_space_default) {
2251                 if (use_booktabs)
2252                         os << "\\addlinespace\n";
2253                 else
2254                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2255                 ++ret;
2256         } else if(!row_info[i].top_space.zero()) {
2257                 if (use_booktabs)
2258                         os << "\\addlinespace["
2259                            << from_ascii(row_info[i].top_space.asLatexString())
2260                            << "]\n";
2261                 else {
2262                         os << "\\noalign{\\vskip"
2263                            << from_ascii(row_info[i].top_space.asLatexString())
2264                            << "}\n";
2265                 }
2266                 ++ret;
2267         }
2268         bool ismulticol = false;
2269         for (col_type j = 0; j < column_info.size(); ++j) {
2270                 if (isPartOfMultiColumn(i, j))
2271                         continue;
2272                 ret += TeXCellPreamble(os, cell, ismulticol);
2273                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2274
2275                 Paragraph const & par = inset->paragraphs().front();
2276                 bool rtl = par.isRTL(buffer().params())
2277                         && !par.empty()
2278                         && getPWidth(cell).zero();
2279
2280                 if (rtl) {
2281                         string const lang =
2282                                 par.getParLanguage(buffer().params())->lang();
2283                         if (lang == "farsi")
2284                                 os << "\\textFR{";
2285                         else if (lang == "arabic_arabi")
2286                                 os << "\\textAR{";
2287                         // currently, remaning RTL languages are
2288                         // arabic_arabtex and hebrew
2289                         else
2290                                 os << "\\R{";
2291                 }
2292                 // pass to the OutputParams that we are in a cell and
2293                 // which alignment we have set.
2294                 // InsetNewline needs this context information.
2295                 OutputParams newrp(runparams);
2296                 newrp.inTableCell = (getAlignment(cell) == LYX_ALIGN_BLOCK)
2297                                     ? OutputParams::PLAIN
2298                                     : OutputParams::ALIGNED;
2299                 ret += inset->latex(os, newrp);
2300                 runparams.encoding = newrp.encoding;
2301                 if (rtl)
2302                         os << '}';
2303
2304                 ret += TeXCellPostamble(os, cell, ismulticol);
2305                 if (!isLastCellInRow(cell)) { // not last cell in row
2306                         os << " & ";
2307                 }
2308                 ++cell;
2309         }
2310         os << "\\tabularnewline";
2311         if (row_info[i].bottom_space_default) {
2312                 if (use_booktabs)
2313                         os << "\\addlinespace";
2314                 else
2315                         os << "[\\doublerulesep]";
2316         } else if (!row_info[i].bottom_space.zero()) {
2317                 if (use_booktabs)
2318                         os << "\\addlinespace";
2319                 os << '['
2320                    << from_ascii(row_info[i].bottom_space.asLatexString())
2321                    << ']';
2322         }
2323         os << '\n';
2324         ++ret;
2325
2326         //output the bottom line
2327         ret += TeXBottomHLine(os, i, lang);
2328
2329         if (row_info[i].interline_space_default) {
2330                 if (use_booktabs)
2331                         os << "\\addlinespace\n";
2332                 else
2333                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2334                 ++ret;
2335         } else if (!row_info[i].interline_space.zero()) {
2336                 if (use_booktabs)
2337                         os << "\\addlinespace["
2338                            << from_ascii(row_info[i].interline_space.asLatexString())
2339                            << "]\n";
2340                 else
2341                         os << "\\noalign{\\vskip"
2342                            << from_ascii(row_info[i].interline_space.asLatexString())
2343                            << "}\n";
2344                 ++ret;
2345         }
2346         return ret;
2347 }
2348
2349
2350 int Tabular::latex(odocstream & os, OutputParams const & runparams) const
2351 {
2352         int ret = 0;
2353
2354         //+---------------------------------------------------------------------
2355         //+                      first the opening preamble                    +
2356         //+---------------------------------------------------------------------
2357
2358         if (rotate) {
2359                 os << "\\begin{sideways}\n";
2360                 ++ret;
2361         }
2362         if (is_long_tabular) {
2363                 os << "\\begin{longtable}";
2364                 switch (longtabular_alignment) {
2365                 case LYX_LONGTABULAR_ALIGN_LEFT:
2366                         os << "[l]";
2367                         break;
2368                 case LYX_LONGTABULAR_ALIGN_CENTER:
2369                         break;
2370                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2371                         os << "[r]";
2372                         break;
2373                 }
2374         } else {
2375                 os << "\\begin{tabular}";
2376                 switch (tabular_valignment) {
2377                 case LYX_VALIGN_TOP:
2378                         os << "[t]";
2379                         break;
2380                 case LYX_VALIGN_MIDDLE:
2381                         break;
2382                 case LYX_VALIGN_BOTTOM:
2383                         os << "[b]";
2384                         break;
2385                 }
2386         }
2387         
2388         os << "{";
2389
2390         for (col_type i = 0; i < column_info.size(); ++i) {
2391                 if (columnLeftLine(i))
2392                         os << '|';
2393                 if (!column_info[i].align_special.empty()) {
2394                         os << column_info[i].align_special;
2395                 } else {
2396                         if (!column_info[i].p_width.zero()) {
2397                                 switch (column_info[i].alignment) {
2398                                 case LYX_ALIGN_LEFT:
2399                                         os << ">{\\raggedright}";
2400                                         break;
2401                                 case LYX_ALIGN_RIGHT:
2402                                         os << ">{\\raggedleft}";
2403                                         break;
2404                                 case LYX_ALIGN_CENTER:
2405                                         os << ">{\\centering}";
2406                                         break;
2407                                 case LYX_ALIGN_NONE:
2408                                 case LYX_ALIGN_BLOCK:
2409                                 case LYX_ALIGN_LAYOUT:
2410                                 case LYX_ALIGN_SPECIAL:
2411                                         break;
2412                                 }
2413
2414                                 switch (column_info[i].valignment) {
2415                                 case LYX_VALIGN_TOP:
2416                                         os << 'p';
2417                                         break;
2418                                 case LYX_VALIGN_MIDDLE:
2419                                         os << 'm';
2420                                         break;
2421                                 case LYX_VALIGN_BOTTOM:
2422                                         os << 'b';
2423                                         break;
2424                         }
2425                                 os << '{'
2426                                    << from_ascii(column_info[i].p_width.asLatexString())
2427                                    << '}';
2428                         } else {
2429                                 switch (column_info[i].alignment) {
2430                                 case LYX_ALIGN_LEFT:
2431                                         os << 'l';
2432                                         break;
2433                                 case LYX_ALIGN_RIGHT:
2434                                         os << 'r';
2435                                         break;
2436                                 default:
2437                                         os << 'c';
2438                                         break;
2439                                 }
2440                         } // end if else !column_info[i].p_width
2441                 } // end if else !column_info[i].align_special
2442                 if (columnRightLine(i))
2443                         os << '|';
2444         }
2445         os << "}\n";
2446         ++ret;
2447
2448         ret += TeXLongtableHeaderFooter(os, runparams);
2449
2450         //+---------------------------------------------------------------------
2451         //+                      the single row and columns (cells)            +
2452         //+---------------------------------------------------------------------
2453
2454         for (row_type i = 0; i < row_info.size(); ++i) {
2455                 if (isValidRow(i)) {
2456                         ret += TeXRow(os, i, runparams);
2457                         if (is_long_tabular && row_info[i].newpage) {
2458                                 os << "\\newpage\n";
2459                                 ++ret;
2460                         }
2461                 }
2462         }
2463
2464         //+---------------------------------------------------------------------
2465         //+                      the closing of the tabular                    +
2466         //+---------------------------------------------------------------------
2467
2468         if (is_long_tabular)
2469                 os << "\\end{longtable}";
2470         else
2471                 os << "\\end{tabular}";
2472         if (rotate) {
2473                 os << "\n\\end{sideways}";
2474                 ++ret;
2475         }
2476
2477         return ret;
2478 }
2479
2480
2481 int Tabular::docbookRow(odocstream & os, row_type row,
2482                            OutputParams const & runparams) const
2483 {
2484         int ret = 0;
2485         idx_type cell = getFirstCellInRow(row);
2486
2487         os << "<row>\n";
2488         for (col_type j = 0; j < column_info.size(); ++j) {
2489                 if (isPartOfMultiColumn(row, j))
2490                         continue;
2491
2492                 os << "<entry align=\"";
2493                 switch (getAlignment(cell)) {
2494                 case LYX_ALIGN_LEFT:
2495                         os << "left";
2496                         break;
2497                 case LYX_ALIGN_RIGHT:
2498                         os << "right";
2499                         break;
2500                 default:
2501                         os << "center";
2502                         break;
2503                 }
2504
2505                 os << "\" valign=\"";
2506                 switch (getVAlignment(cell)) {
2507                 case LYX_VALIGN_TOP:
2508                         os << "top";
2509                         break;
2510                 case LYX_VALIGN_BOTTOM:
2511                         os << "bottom";
2512                         break;
2513                 case LYX_VALIGN_MIDDLE:
2514                         os << "middle";
2515                 }
2516                 os << '"';
2517
2518                 if (isMultiColumn(cell)) {
2519                         os << " namest=\"col" << j << "\" ";
2520                         os << "nameend=\"col" << j + columnSpan(cell) - 1<< '"';
2521                 }
2522
2523                 os << '>';
2524                 ret += cellInset(cell)->docbook(os, runparams);
2525                 os << "</entry>\n";
2526                 ++cell;
2527         }
2528         os << "</row>\n";
2529         return ret;
2530 }
2531
2532
2533 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2534 {
2535         int ret = 0;
2536
2537         //+---------------------------------------------------------------------
2538         //+                      first the opening preamble                    +
2539         //+---------------------------------------------------------------------
2540
2541         os << "<tgroup cols=\"" << column_info.size()
2542            << "\" colsep=\"1\" rowsep=\"1\">\n";
2543
2544         for (col_type i = 0; i < column_info.size(); ++i) {
2545                 os << "<colspec colname=\"col" << i << "\" align=\"";
2546                 switch (column_info[i].alignment) {
2547                 case LYX_ALIGN_LEFT:
2548                         os << "left";
2549                         break;
2550                 case LYX_ALIGN_RIGHT:
2551                         os << "right";
2552                         break;
2553                 default:
2554                         os << "center";
2555                         break;
2556                 }
2557                 os << '"';
2558                 if (runparams.flavor == OutputParams::XML)
2559                         os << '/';
2560                 os << ">\n";
2561                 ++ret;
2562         }
2563
2564         //+---------------------------------------------------------------------
2565         //+                      Long Tabular case                             +
2566         //+---------------------------------------------------------------------
2567
2568         // output caption info
2569         if (haveLTCaption()) {
2570                 os << "<caption>\n";
2571                 ++ret;
2572                 for (row_type i = 0; i < row_info.size(); ++i) {
2573                         if (row_info[i].caption) {
2574                                 ret += docbookRow(os, i, runparams);
2575                         }
2576                 }
2577                 os << "</caption>\n";
2578                 ++ret;
2579         }
2580         // output header info
2581         if (haveLTHead() || haveLTFirstHead()) {
2582                 os << "<thead>\n";
2583                 ++ret;
2584                 for (row_type i = 0; i < row_info.size(); ++i) {
2585                         if (row_info[i].endhead || row_info[i].endfirsthead) {
2586                                 ret += docbookRow(os, i, runparams);
2587                         }
2588                 }
2589                 os << "</thead>\n";
2590                 ++ret;
2591         }
2592         // output footer info
2593         if (haveLTFoot() || haveLTLastFoot()) {
2594                 os << "<tfoot>\n";
2595                 ++ret;
2596                 for (row_type i = 0; i < row_info.size(); ++i) {
2597                         if (row_info[i].endfoot || row_info[i].endlastfoot) {
2598                                 ret += docbookRow(os, i, runparams);
2599                         }
2600                 }
2601                 os << "</tfoot>\n";
2602                 ++ret;
2603         }
2604
2605         //+---------------------------------------------------------------------
2606         //+                      the single row and columns (cells)            +
2607         //+---------------------------------------------------------------------
2608
2609         os << "<tbody>\n";
2610         ++ret;
2611         for (row_type i = 0; i < row_info.size(); ++i) {
2612                 if (isValidRow(i)) {
2613                         ret += docbookRow(os, i, runparams);
2614                 }
2615         }
2616         os << "</tbody>\n";
2617         ++ret;
2618         //+---------------------------------------------------------------------
2619         //+                      the closing of the tabular                    +
2620         //+---------------------------------------------------------------------
2621
2622         os << "</tgroup>";
2623         ++ret;
2624
2625         return ret;
2626 }
2627
2628
2629 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2630                                    vector<unsigned int> const & clen) const
2631 {
2632         idx_type const fcell = getFirstCellInRow(row);
2633         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2634         idx_type tmp = 0;
2635
2636         for (idx_type i = fcell; i < n; ++i) {
2637                 if (topLine(i)) {
2638                         ++tmp;
2639                         break;
2640                 }
2641         }
2642         if (!tmp)
2643                 return false;
2644
2645         char_type ch;
2646         for (idx_type i = fcell; i < n; ++i) {
2647                 if (topLine(i)) {
2648                         if (leftLine(i))
2649                                 os << "+-";
2650                         else
2651                                 os << "--";
2652                         ch = '-';
2653                 } else {
2654                         os << "  ";
2655                         ch = ' ';
2656                 }
2657                 col_type column = cellColumn(i);
2658                 int len = clen[column];
2659                 while (column < column_info.size() - 1
2660                        && isPartOfMultiColumn(row, ++column))
2661                         len += clen[column] + 4;
2662                 os << docstring(len, ch);
2663                 if (topLine(i)) {
2664                         if (rightLine(i))
2665                                 os << "-+";
2666                         else
2667                                 os << "--";
2668                 } else {
2669                         os << "  ";
2670                 }
2671         }
2672         os << endl;
2673         return true;
2674 }
2675
2676
2677 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2678                                       vector<unsigned int> const & clen) const
2679 {
2680         idx_type const fcell = getFirstCellInRow(row);
2681         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2682         idx_type tmp = 0;
2683
2684         for (idx_type i = fcell; i < n; ++i) {
2685                 if (bottomLine(i)) {
2686                         ++tmp;
2687                         break;
2688                 }
2689         }
2690         if (!tmp)
2691                 return false;
2692
2693         char_type ch;
2694         for (idx_type i = fcell; i < n; ++i) {
2695                 if (bottomLine(i)) {
2696                         if (leftLine(i))
2697                                 os << "+-";
2698                         else
2699                                 os << "--";
2700                         ch = '-';
2701                 } else {
2702                         os << "  ";
2703                         ch = ' ';
2704                 }
2705                 col_type column = cellColumn(i);
2706                 int len = clen[column];
2707                 while (column < column_info.size() -1
2708                        && isPartOfMultiColumn(row, ++column))
2709                         len += clen[column] + 4;
2710                 os << docstring(len, ch);
2711                 if (bottomLine(i)) {
2712                         if (rightLine(i))
2713                                 os << "-+";
2714                         else
2715                                 os << "--";
2716                 } else {
2717                         os << "  ";
2718                 }
2719         }
2720         os << endl;
2721         return true;
2722 }
2723
2724
2725 void Tabular::plaintextPrintCell(odocstream & os,
2726                                OutputParams const & runparams,
2727                                idx_type cell, row_type row, col_type column,
2728                                vector<unsigned int> const & clen,
2729                                bool onlydata) const
2730 {
2731         odocstringstream sstr;
2732         cellInset(cell)->plaintext(sstr, runparams);
2733
2734         if (onlydata) {
2735                 os << sstr.str();
2736                 return;
2737         }
2738
2739         if (leftLine(cell))
2740                 os << "| ";
2741         else
2742                 os << "  ";
2743
2744         unsigned int len1 = sstr.str().length();
2745         unsigned int len2 = clen[column];
2746         while (column < column_info.size() -1
2747                && isPartOfMultiColumn(row, ++column))
2748                 len2 += clen[column] + 4;
2749         len2 -= len1;
2750
2751         switch (getAlignment(cell)) {
2752         default:
2753         case LYX_ALIGN_LEFT:
2754                 len1 = 0;
2755                 break;
2756         case LYX_ALIGN_RIGHT:
2757                 len1 = len2;
2758                 len2 = 0;
2759                 break;
2760         case LYX_ALIGN_CENTER:
2761                 len1 = len2 / 2;
2762                 len2 -= len1;
2763                 break;
2764         }
2765
2766         os << docstring(len1, ' ') << sstr.str()
2767            << docstring(len2, ' ');
2768
2769         if (rightLine(cell))
2770                 os << " |";
2771         else
2772                 os << "  ";
2773 }
2774
2775
2776 void Tabular::plaintext(odocstream & os,
2777                            OutputParams const & runparams, int const depth,
2778                            bool onlydata, char_type delim) const
2779 {
2780         // first calculate the width of the single columns
2781         vector<unsigned int> clen(column_info.size());
2782
2783         if (!onlydata) {
2784                 // first all non (real) multicolumn cells!
2785                 for (col_type j = 0; j < column_info.size(); ++j) {
2786                         clen[j] = 0;
2787                         for (row_type i = 0; i < row_info.size(); ++i) {
2788                                 idx_type cell = cellIndex(i, j);
2789                                 if (isMultiColumnReal(cell))
2790                                         continue;
2791                                 odocstringstream sstr;
2792                                 cellInset(cell)->plaintext(sstr, runparams);
2793                                 if (clen[j] < sstr.str().length())
2794                                         clen[j] = sstr.str().length();
2795                         }
2796                 }
2797                 // then all (real) multicolumn cells!
2798                 for (col_type j = 0; j < column_info.size(); ++j) {
2799                         for (row_type i = 0; i < row_info.size(); ++i) {
2800                                 idx_type cell = cellIndex(i, j);
2801                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2802                                         continue;
2803                                 odocstringstream sstr;
2804                                 cellInset(cell)->plaintext(sstr, runparams);
2805                                 int len = int(sstr.str().length());
2806                                 idx_type const n = columnSpan(cell);
2807                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2808                                         len -= clen[k];
2809                                 if (len > int(clen[j + n - 1]))
2810                                         clen[j + n - 1] = len;
2811                         }
2812                 }
2813         }
2814         idx_type cell = 0;
2815         for (row_type i = 0; i < row_info.size(); ++i) {
2816                 if (!onlydata && plaintextTopHLine(os, i, clen))
2817                         os << docstring(depth * 2, ' ');
2818                 for (col_type j = 0; j < column_info.size(); ++j) {
2819                         if (isPartOfMultiColumn(i, j))
2820                                 continue;
2821                         if (onlydata && j > 0)
2822                                 // we don't use operator<< for single UCS4 character.
2823                                 // see explanation in docstream.h
2824                                 os.put(delim);
2825                         plaintextPrintCell(os, runparams, cell, i, j, clen, onlydata);
2826                         ++cell;
2827                 }
2828                 os << endl;
2829                 if (!onlydata) {
2830                         os << docstring(depth * 2, ' ');
2831                         if (plaintextBottomHLine(os, i, clen))
2832                                 os << docstring(depth * 2, ' ');
2833                 }
2834         }
2835 }
2836
2837
2838 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
2839 {
2840         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2841 }
2842
2843
2844 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
2845                                                col_type column) const
2846 {
2847         return cell_info[row][column].inset;
2848 }
2849
2850
2851 void Tabular::setCellInset(row_type row, col_type column,
2852                               shared_ptr<InsetTableCell> ins) const
2853 {
2854         CellData & cd = cell_info[row][column];
2855         cd.inset = ins;
2856 }
2857
2858
2859 void Tabular::validate(LaTeXFeatures & features) const
2860 {
2861         features.require("NeedTabularnewline");
2862         if (use_booktabs)
2863                 features.require("booktabs");
2864         if (is_long_tabular)
2865                 features.require("longtable");
2866         if (needRotating())
2867                 features.require("rotating");
2868         for (idx_type cell = 0; cell < numberofcells; ++cell) {
2869                 if (getVAlignment(cell) != LYX_VALIGN_TOP
2870                     || !getPWidth(cell).zero())
2871                         features.require("array");
2872                 cellInset(cell)->validate(features);
2873         }
2874 }
2875
2876
2877 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2878 {
2879         ParagraphList const & parlist = cellInset(cell)->paragraphs();
2880         ParagraphList::const_iterator cit = parlist.begin();
2881         ParagraphList::const_iterator end = parlist.end();
2882
2883         for (; cit != end; ++cit)
2884                 for (int i = 0; i < cit->size(); ++i)
2885                         if (cit->isNewline(i))
2886                                 return BOX_PARBOX;
2887
2888         return BOX_NONE;
2889 }
2890
2891
2892 /////////////////////////////////////////////////////////////////////
2893 //
2894 // InsetTableCell
2895 //
2896 /////////////////////////////////////////////////////////////////////
2897
2898 InsetTableCell::InsetTableCell(Buffer & buf)
2899         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
2900           contentAlign(LYX_ALIGN_CENTER)
2901 {}
2902
2903
2904 bool InsetTableCell::forcePlainLayout(idx_type) const
2905 {
2906         return !isFixedWidth;
2907 }
2908
2909
2910 bool InsetTableCell::allowParagraphCustomization(idx_type) const
2911 {
2912         return isFixedWidth;
2913 }
2914
2915
2916 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
2917         FuncStatus & status) const
2918 {
2919         bool enabled;
2920         switch (cmd.action) {
2921         case LFUN_LAYOUT:
2922                 enabled = !forcePlainLayout();
2923                 break;
2924         case LFUN_LAYOUT_PARAGRAPH:
2925                 enabled = allowParagraphCustomization();
2926                 break;
2927         default:
2928                 return InsetText::getStatus(cur, cmd, status);
2929         }
2930         status.setEnabled(enabled);
2931         return true;
2932 }
2933
2934 docstring InsetTableCell::asString(bool intoInsets) 
2935 {
2936         docstring retval;
2937         if (paragraphs().empty())
2938                 return retval;
2939         ParagraphList::const_iterator it = paragraphs().begin();
2940         ParagraphList::const_iterator en = paragraphs().end();
2941         bool first = true;
2942         for (; it != en; ++it) {
2943                 if (!first)
2944                         retval += "\n";
2945                 else
2946                         first = false;
2947                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
2948         }
2949         return retval;
2950 }
2951
2952
2953
2954 /////////////////////////////////////////////////////////////////////
2955 //
2956 // InsetTabular
2957 //
2958 /////////////////////////////////////////////////////////////////////
2959
2960 InsetTabular::InsetTabular(Buffer & buf, row_type rows,
2961                            col_type columns)
2962         : tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
2963         rowselect_(false), colselect_(false)
2964 {
2965         setBuffer(buf); // FIXME: remove later
2966 }
2967
2968
2969 InsetTabular::InsetTabular(InsetTabular const & tab)
2970         : Inset(tab), tabular(tab.tabular),  scx_(0)
2971 {
2972 }
2973
2974
2975 InsetTabular::~InsetTabular()
2976 {
2977         hideDialogs("tabular", this);
2978 }
2979
2980
2981 void InsetTabular::setBuffer(Buffer & buf)
2982 {
2983         tabular.setBuffer(buf);
2984         Inset::setBuffer(buf);
2985 }
2986
2987
2988 bool InsetTabular::insetAllowed(InsetCode code) const
2989 {
2990         if (code == MATHMACRO_CODE
2991                 || (code == CAPTION_CODE && !tabular.is_long_tabular))
2992                 return false;
2993
2994         return true;
2995 }
2996
2997
2998 void InsetTabular::write(ostream & os) const
2999 {
3000         os << "Tabular" << endl;
3001         tabular.write(os);
3002 }
3003
3004
3005 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
3006 {
3007         // FIXME: depending on the selection state, we could offer a different menu.
3008         return from_ascii("context-tabular");
3009 }
3010
3011
3012 void InsetTabular::read(Lexer & lex)
3013 {
3014         //bool const old_format = (lex.getString() == "\\LyXTable");
3015
3016         tabular.read(lex);
3017
3018         //if (old_format)
3019         //      return;
3020
3021         lex.next();
3022         string token = lex.getString();
3023         while (lex && token != "\\end_inset") {
3024                 lex.next();
3025                 token = lex.getString();
3026         }
3027         if (!lex)
3028                 lex.printError("Missing \\end_inset at this point. ");
3029 }
3030
3031
3032 int InsetTabular::rowFromY(Cursor & cur, int y) const
3033 {
3034         // top y coordinate of tabular
3035         int h = yo(cur.bv()) - tabular.rowAscent(0);
3036         size_t nrows = tabular.row_info.size();
3037         row_type r = 0;
3038         for (; r < nrows && y > h; ++r) {
3039                 h += tabular.rowAscent(r);
3040                 h += tabular.rowDescent(r);
3041                 h += tabular.getAdditionalHeight(r);
3042         }
3043         return r - 1;
3044 }
3045
3046
3047 int InsetTabular::columnFromX(Cursor & cur, int x) const
3048 {
3049         // left x coordinate of tabular
3050         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3051         size_t ncols = tabular.column_info.size();
3052         col_type c = 0;
3053         for (; c < ncols && x > w; ++c)
3054                 w += tabular.columnWidth(c);
3055         return c - 1;
3056 }
3057
3058
3059 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3060 {
3061         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3062         //      mi.base.textwidth << "\n";
3063         if (!mi.base.bv) {
3064                 LYXERR0("need bv");
3065                 LASSERT(false, /**/);
3066         }
3067
3068         row_type i = 0;
3069         for (idx_type cell = 0; i < tabular.row_info.size(); ++i) {
3070                 int maxAsc = 0;
3071                 int maxDesc = 0;
3072                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3073                         if (tabular.isPartOfMultiColumn(i, j))
3074                                 // Multicolumn cell, but not first one
3075                                 continue;
3076                         Dimension dim;
3077                         MetricsInfo m = mi;
3078                         Length p_width;
3079                         if (tabular.cell_info[i][j].multicolumn ==
3080                                 Tabular::CELL_BEGIN_OF_MULTICOLUMN)
3081                                 p_width = tabular.cellInfo(cell).p_width;
3082                         else
3083                                 p_width = tabular.column_info[j].p_width;
3084                         if (!p_width.zero())
3085                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3086                         tabular.cellInset(cell)->metrics(m, dim);
3087                         if (!p_width.zero())
3088                                 dim.wid = m.base.textwidth;
3089                         tabular.setCellWidth(cell, dim.wid);
3090                         maxAsc  = max(maxAsc, dim.asc);
3091                         maxDesc = max(maxDesc, dim.des);
3092                         ++cell;
3093                 }
3094                 int const top_space = tabular.row_info[i].top_space_default ?
3095                         default_line_space :
3096                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
3097                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
3098                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
3099                         default_line_space :
3100                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
3101                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
3102         }
3103         tabular.updateColumnWidths();
3104         dim.asc = tabular.rowAscent(0);
3105         dim.des = tabular.height() - dim.asc;
3106         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3107 }
3108
3109 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3110         const
3111 {
3112         if (&cur.inset() == this && cur.selection()) {
3113                 if (cur.selIsMultiCell()) {
3114                         row_type rs, re;
3115                         col_type cs, ce;
3116                         getSelection(cur, rs, re, cs, ce);
3117                         
3118                         if (col >= cs && col <= ce && row >= rs && row <= re)
3119                                 return true;
3120                 } else 
3121                         if (col == tabular.cellColumn(cur.idx()) 
3122                                 && row == tabular.cellRow(cur.idx())) {
3123                         CursorSlice const & beg = cur.selBegin();
3124                         CursorSlice const & end = cur.selEnd();
3125
3126                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3127                                   && end.pos() == end.lastpos() && beg.pos() == 0
3128                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3129                                 return true;
3130                 }
3131         }
3132         return false;
3133 }
3134
3135
3136 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3137 {
3138         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
3139         BufferView * bv = pi.base.bv;
3140         Cursor & cur = pi.base.bv->cursor();
3141
3142         // FIXME: As the full background is painted in drawSelection(),
3143         // we have no choice but to do a full repaint for the Text cells.
3144         pi.full_repaint = true;
3145
3146         resetPos(bv->cursor());
3147
3148         x += scx_;
3149         x += ADD_TO_TABULAR_WIDTH;
3150
3151         bool const original_drawing_state = pi.pain.isDrawingEnabled();
3152         bool const original_selection_state = pi.selected;
3153
3154         idx_type idx = 0;
3155         first_visible_cell = Tabular::npos;
3156         for (row_type i = 0; i < tabular.row_info.size(); ++i) {
3157                 int nx = x;
3158                 int const a = tabular.rowAscent(i);
3159                 int const d = tabular.rowDescent(i);
3160                 idx = tabular.cellIndex(i, 0);
3161                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3162                         if (tabular.isPartOfMultiColumn(i, j))
3163                                 continue;
3164                         if (first_visible_cell == Tabular::npos)
3165                                 first_visible_cell = idx;
3166
3167                         pi.selected |= isCellSelected(cur, i, j);
3168                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
3169                         // Cache the Inset position.
3170                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
3171                         if (nx + tabular.columnWidth(idx) < 0
3172                             || nx > bv->workWidth()
3173                             || y + d < 0
3174                             || y - a > bv->workHeight()) {
3175                                 pi.pain.setDrawingEnabled(false);
3176                                 cell(idx)->draw(pi, cx, y);
3177                                 drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
3178                                 pi.pain.setDrawingEnabled(original_drawing_state);
3179                         } else {
3180                                 cell(idx)->draw(pi, cx, y);
3181                                 drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
3182                         }
3183                         nx += tabular.columnWidth(idx);
3184                         ++idx;
3185                         pi.selected = original_selection_state;
3186                 }
3187
3188                 if (i + 1 < tabular.row_info.size())
3189                         y += d + tabular.rowAscent(i + 1) +
3190                                 tabular.getAdditionalHeight(i + 1);
3191         }
3192 }
3193
3194
3195 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3196 {
3197         Cursor & cur = pi.base.bv->cursor();
3198         resetPos(cur);
3199
3200         x += scx_ + ADD_TO_TABULAR_WIDTH;
3201
3202         // FIXME: it is wrong to completely paint the background
3203         // if we want to do single row painting.
3204
3205         // Paint background of current tabular
3206         int const w = tabular.width();
3207         int const h = tabular.height();
3208         int yy = y - tabular.rowAscent(0);
3209         pi.pain.fillRectangle(x, yy, w, h, pi.backgroundColor(this));
3210
3211         if (!cur.selection())
3212                 return;
3213         if (&cur.inset() != this)
3214                 return;
3215
3216         //resetPos(cur);
3217
3218         bool const full_cell_selected = isCellSelected(cur,
3219                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3220
3221         if (cur.selIsMultiCell() || full_cell_selected) {
3222                 y -= tabular.rowAscent(0);
3223                 for (row_type j = 0; j < tabular.row_info.size(); ++j) {
3224                         int const a = tabular.rowAscent(j);
3225                         int const h = a + tabular.rowDescent(j);
3226                         int xx = x;
3227                         y += tabular.getAdditionalHeight(j);
3228                         for (col_type i = 0; i < tabular.column_info.size(); ++i) {
3229                                 if (tabular.isPartOfMultiColumn(j, i))
3230                                         continue;
3231                                 idx_type const cell =
3232                                         tabular.cellIndex(j, i);
3233                                 int const w = tabular.columnWidth(cell);
3234                                 if (isCellSelected(cur, j, i))
3235                                         pi.pain.fillRectangle(xx, y, w, h, Color_selection);
3236                                 xx += w;
3237                         }
3238                         y += h;
3239                 }
3240
3241         } else {
3242                 x += cellXPos(cur.idx());
3243                 x += tabular.getBeginningOfTextInCell(cur.idx());
3244                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3245         }
3246 }
3247
3248
3249 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3250                                  row_type row, idx_type cell, Change const & change) const
3251 {
3252         int x2 = x + tabular.columnWidth(cell);
3253         bool on_off = false;
3254         Color col = Color_tabularline;
3255         Color onoffcol = Color_tabularonoffline;
3256
3257         if (change.changed()) {
3258                 col = change.color();
3259                 onoffcol = change.color();
3260         }
3261
3262         if (!tabular.topAlreadyDrawn(cell)) {
3263                 on_off = !tabular.topLine(cell);
3264                 pain.line(x, y - tabular.rowAscent(row),
3265                           x2, y -  tabular.rowAscent(row),
3266                           on_off ? onoffcol : col,
3267                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3268         }
3269         on_off = !tabular.bottomLine(cell);
3270         pain.line(x, y + tabular.rowDescent(row),
3271                   x2, y + tabular.rowDescent(row),
3272                   on_off ? onoffcol : col,
3273                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3274         if (!tabular.leftAlreadyDrawn(cell)) {
3275                 on_off = !tabular.leftLine(cell);
3276                 pain.line(x, y -  tabular.rowAscent(row),
3277                           x, y +  tabular.rowDescent(row),
3278                           on_off ? onoffcol : col,
3279                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3280         }
3281         on_off = !tabular.rightLine(cell);
3282         pain.line(x2 - tabular.getAdditionalWidth(cell),
3283                   y -  tabular.rowAscent(row),
3284                   x2 - tabular.getAdditionalWidth(cell),
3285                   y +  tabular.rowDescent(row),
3286                   on_off ? onoffcol : col,
3287                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3288 }
3289
3290
3291 docstring InsetTabular::editMessage() const
3292 {
3293         return _("Opened table");
3294 }
3295
3296
3297 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3298 {
3299         //lyxerr << "InsetTabular::edit: " << this << endl;
3300         cur.finishUndo();
3301         cur.setSelection(false);
3302         cur.push(*this);
3303         if (front) {
3304                 if (isRightToLeft(cur))
3305                         cur.idx() = tabular.getLastCellInRow(0);
3306                 else
3307                         cur.idx() = 0;
3308                 cur.pit() = 0;
3309                 cur.pos() = 0;
3310         } else {
3311                 if (isRightToLeft(cur))
3312                         cur.idx() = tabular.getFirstCellInRow(tabular.row_info.size() - 1);
3313                 else
3314                         cur.idx() = tabular.numberofcells - 1;
3315                 cur.pit() = 0;
3316                 cur.pos() = cur.lastpos(); // FIXME crude guess
3317         }
3318         // FIXME: this accesses the position cache before it is initialized
3319         //resetPos(cur);
3320         //cur.bv().fitCursor();
3321 }
3322
3323
3324 void InsetTabular::updateLabels(ParIterator const & it)
3325 {
3326         // In a longtable, tell captions what the current float is
3327         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3328         string const saveflt = cnts.current_float();
3329         if (tabular.is_long_tabular)
3330                 cnts.current_float("table");
3331
3332         ParIterator it2 = it;
3333         it2.forwardPos();
3334         size_t const end = it2.nargs();
3335         for ( ; it2.idx() < end; it2.top().forwardIdx())
3336                 buffer().updateLabels(it2);
3337
3338         //reset afterwards
3339         if (tabular.is_long_tabular)
3340                 cnts.current_float(saveflt);
3341 }
3342
3343
3344 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3345 {
3346         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3347                              << "\n  cur:" << cur);
3348         CursorSlice sl = cur.top();
3349         Cursor & bvcur = cur.bv().cursor();
3350
3351         switch (cmd.action) {
3352
3353         case LFUN_MOUSE_PRESS: {
3354                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3355                 // select row
3356                 if (cmd.x < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3357                         || cmd.x > xo(cur.bv()) + tabular.width()) {
3358                         row_type r = rowFromY(cur, cmd.y);
3359                         cur.idx() = tabular.getFirstCellInRow(r);
3360                         cur.pos() = 0;
3361                         cur.resetAnchor();
3362                         cur.idx() = tabular.getLastCellInRow(r);
3363                         cur.pos() = cur.lastpos();
3364                         cur.setSelection(true);
3365                         bvcur = cur; 
3366                         rowselect_ = true;
3367                         break;
3368                 }
3369                 // select column
3370                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3371                 if (cmd.y < y0 + ADD_TO_TABULAR_WIDTH 
3372                         || cmd.y > y0 + tabular.height()) {
3373                         col_type c = columnFromX(cur, cmd.x);
3374                         cur.idx() = tabular.cellIndex(0, c);
3375                         cur.pos() = 0;
3376                         cur.resetAnchor();
3377                         cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3378                         cur.pos() = cur.lastpos();
3379                         cur.setSelection(true);
3380                         bvcur = cur; 
3381                         colselect_ = true;
3382                         break;
3383                 }
3384                 // do not reset cursor/selection if we have selected
3385                 // some cells (bug 2715).
3386                 if (cmd.button() == mouse_button::button3
3387                     && &bvcur.selBegin().inset() == this 
3388                     && bvcur.selIsMultiCell()) 
3389                         ;
3390                 else
3391                         // Let InsetTableCell do it
3392                         cell(cur.idx())->dispatch(cur, cmd);
3393                 break;
3394         }
3395         case LFUN_MOUSE_MOTION:
3396                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3397                 if (cmd.button() == mouse_button::button1) {
3398                         // only accept motions to places not deeper nested than the real anchor
3399                         if (!bvcur.anchor_.hasPart(cur)) {
3400                                 cur.undispatched();
3401                                 break;
3402                         }
3403                         // select (additional) row
3404                         if (rowselect_) {
3405                                 row_type r = rowFromY(cur, cmd.y);
3406                                 cur.idx() = tabular.getLastCellInRow(r);
3407                                 // we need to reset the cursor's pit and pos now, as the old ones
3408                                 // may no longer be valid.
3409                                 cur.pit() = 0;
3410                                 cur.pos() = 0;
3411                                 bvcur.setCursor(cur);
3412                                 bvcur.setSelection(true);
3413                                 break;
3414                         }
3415                         // select (additional) column
3416                         if (colselect_) {
3417                                 col_type c = columnFromX(cur, cmd.x);
3418                                 cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3419                                 // we need to reset the cursor's pit and pos now, as the old ones
3420                                 // may no longer be valid.
3421                                 cur.pit() = 0;
3422                                 cur.pos() = 0;
3423                                 bvcur.setCursor(cur);
3424                                 bvcur.setSelection(true);
3425                                 break;
3426                         }
3427                         // only update if selection changes
3428                         if (bvcur.idx() == cur.idx() &&
3429                                 !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3430                                 cur.noUpdate();
3431                         setCursorFromCoordinates(cur, cmd.x, cmd.y);
3432                         bvcur.setCursor(cur);
3433                         bvcur.setSelection(true);
3434                         // if this is a multicell selection, we just set the cursor to
3435                         // the beginning of the cell's text.
3436                         if (bvcur.selIsMultiCell()) {
3437                                 bvcur.pit() = bvcur.lastpit();
3438                                 bvcur.pos() = bvcur.lastpos();
3439                         }
3440                 }
3441                 break;
3442
3443         case LFUN_MOUSE_RELEASE:
3444                 rowselect_ = false;
3445                 colselect_ = false;
3446                 break;
3447
3448         case LFUN_CELL_BACKWARD:
3449                 movePrevCell(cur);
3450                 cur.setSelection(false);
3451                 break;
3452
3453         case LFUN_CELL_FORWARD:
3454                 moveNextCell(cur);
3455                 cur.setSelection(false);
3456                 break;
3457
3458         case LFUN_CHAR_FORWARD_SELECT:
3459         case LFUN_CHAR_FORWARD:
3460         case LFUN_CHAR_BACKWARD_SELECT:
3461         case LFUN_CHAR_BACKWARD:
3462         case LFUN_CHAR_RIGHT_SELECT:
3463         case LFUN_CHAR_RIGHT:
3464         case LFUN_CHAR_LEFT_SELECT:
3465         case LFUN_CHAR_LEFT: {
3466                 // determine whether we move to next or previous cell, where to enter 
3467                 // the new cell from, and which command to "finish" (i.e., exit the
3468                 // inset) with:
3469                 bool next_cell;
3470                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3471                 FuncCode finish_lfun;
3472
3473                 if (cmd.action == LFUN_CHAR_FORWARD 
3474                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
3475                         next_cell = true;
3476                         finish_lfun = LFUN_FINISHED_FORWARD;
3477                 }
3478                 else if (cmd.action == LFUN_CHAR_BACKWARD
3479                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
3480                         next_cell = false;
3481                         finish_lfun = LFUN_FINISHED_BACKWARD;
3482                 }
3483                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3484                 // table's direction.
3485                 else {
3486                         bool const right = cmd.action == LFUN_CHAR_RIGHT
3487                                 || cmd.action == LFUN_CHAR_RIGHT_SELECT;
3488                         next_cell = isRightToLeft(cur) != right;
3489                         
3490                         if (lyxrc.visual_cursor)
3491                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3492
3493                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
3494                 }
3495
3496                 bool const select = cmd.action == LFUN_CHAR_FORWARD_SELECT ||
3497                     cmd.action == LFUN_CHAR_BACKWARD_SELECT ||
3498                     cmd.action == LFUN_CHAR_RIGHT_SELECT ||
3499                     cmd.action == LFUN_CHAR_LEFT_SELECT;
3500
3501                 // If we have a multicell selection or we're 
3502                 // not doing some LFUN_*_SELECT thing anyway...
3503                 if (!cur.selIsMultiCell() || !select) {
3504                         col_type const c = tabular.cellColumn(cur.idx());
3505                         row_type const r = tabular.cellRow(cur.idx());
3506                         // Are we trying to select the whole cell and is the whole cell 
3507                         // not yet selected?
3508                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
3509                                 ((next_cell && cur.pit() == cur.lastpit() 
3510                                 && cur.pos() == cur.lastpos())
3511                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
3512
3513                         // ...try to dispatch to the cell's inset.
3514                         cell(cur.idx())->dispatch(cur, cmd);
3515
3516                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
3517                         
3518                         // When we already have a selection we want to select the whole cell
3519                         // before going to the next cell.
3520                         if (select_whole && !empty_cell){
3521                                 getText(cur.idx())->selectAll(cur);
3522                                 cur.dispatched();
3523                                 break;
3524                         }
3525
3526                         // FIXME: When we support the selection of an empty cell, remove 
3527                         // the !empty_cell from this condition. For now we jump to the next
3528                         // cell if the current cell is empty.
3529                         if (cur.result().dispatched() && !empty_cell)
3530                                 break;
3531                 }
3532
3533                 // move to next/prev cell, as appropriate
3534                 // note that we will always do this if we're selecting and we have
3535                 // a multicell selection
3536                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3537                         << " cell from: " << int(entry_from));
3538                 if (next_cell)
3539                         moveNextCell(cur, entry_from);
3540                 else
3541                         movePrevCell(cur, entry_from);
3542                 // if we're exiting the table, call the appropriate FINISHED lfun
3543                 if (sl == cur.top())
3544                         cmd = FuncRequest(finish_lfun);
3545                 else
3546                         cur.dispatched();
3547                 break;
3548
3549         }
3550
3551         case LFUN_DOWN_SELECT:
3552         case LFUN_DOWN:
3553                 if (!(cur.selection() && cur.selIsMultiCell()))
3554                         cell(cur.idx())->dispatch(cur, cmd);
3555                 
3556                 cur.dispatched(); // override the cell's decision
3557                 if (sl == cur.top()) {
3558                         // if our Text didn't do anything to the cursor
3559                         // then we try to put the cursor into the cell below
3560                         // setting also the right targetX.
3561                         cur.selHandle(cmd.action == LFUN_DOWN_SELECT);
3562                         if (tabular.cellRow(cur.idx()) != tabular.row_info.size() - 1) {
3563                                 cur.idx() = tabular.cellBelow(cur.idx());
3564                                 cur.pit() = 0;
3565                                 TextMetrics const & tm =
3566                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3567                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3568                         }
3569                 }
3570                 if (sl == cur.top()) {
3571                         // we trick it to go to forward after leaving the
3572                         // tabular.
3573                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3574                         cur.undispatched();
3575                 }
3576                 if (cur.selIsMultiCell()) {
3577                         cur.pit() = cur.lastpit();
3578                         cur.pos() = cur.lastpos();
3579                         return;
3580                 }
3581                 break;
3582
3583         case LFUN_UP_SELECT:
3584         case LFUN_UP:
3585                 if (!(cur.selection() && cur.selIsMultiCell()))
3586                         cell(cur.idx())->dispatch(cur, cmd);
3587                 cur.dispatched(); // override the cell's decision
3588                 if (sl == cur.top()) {
3589                         // if our Text didn't do anything to the cursor
3590                         // then we try to put the cursor into the cell above
3591                         // setting also the right targetX.
3592                         cur.selHandle(cmd.action == LFUN_UP_SELECT);
3593                         if (tabular.cellRow(cur.idx()) != 0) {
3594                                 cur.idx() = tabular.cellAbove(cur.idx());
3595                                 cur.pit() = cur.lastpit();
3596                                 Text const * text = cell(cur.idx())->getText(0);
3597                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3598                                 ParagraphMetrics const & pm =
3599                                         tm.parMetrics(cur.lastpit());
3600                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3601                         }
3602                 }
3603                 if (sl == cur.top()) {
3604                         cmd = FuncRequest(LFUN_UP);
3605                         cur.undispatched();
3606                 }
3607                 if (cur.selIsMultiCell()) {
3608                         cur.pit() = 0;
3609                         cur.pos() = cur.lastpos();
3610                         return;
3611                 }
3612                 break;
3613
3614 //      case LFUN_SCREEN_DOWN: {
3615 //              //if (hasSelection())
3616 //              //      cur.selection() = false;
3617 //              col_type const col = tabular.cellColumn(cur.idx());
3618 //              int const t =   cur.bv().top_y() + cur.bv().height();
3619 //              if (t < yo() + tabular.getHeightOfTabular()) {
3620 //                      cur.bv().scrollDocView(t);
3621 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3622 //              } else {
3623 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3624 //              }
3625 //              cur.par() = 0;
3626 //              cur.pos() = 0;
3627 //              break;
3628 //      }
3629 //
3630 //      case LFUN_SCREEN_UP: {
3631 //              //if (hasSelection())
3632 //              //      cur.selection() = false;
3633 //              col_type const col = tabular.cellColumn(cur.idx());
3634 //              int const t =   cur.bv().top_y() + cur.bv().height();
3635 //              if (yo() < 0) {
3636 //                      cur.bv().scrollDocView(t);
3637 //                      if (yo() > 0)
3638 //                              cur.idx() = col;
3639 //                      else
3640 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3641 //              } else {
3642 //                      cur.idx() = col;
3643 //              }
3644 //              cur.par() = cur.lastpar();
3645 //              cur.pos() = cur.lastpos();
3646 //              break;
3647 //      }
3648
3649         case LFUN_LAYOUT_TABULAR:
3650                 cur.bv().showDialog("tabular", params2string(*this), this);
3651                 break;
3652
3653         case LFUN_INSET_DIALOG_UPDATE:
3654                 cur.bv().updateDialog("tabular", params2string(*this));
3655                 break;
3656
3657         case LFUN_TABULAR_FEATURE:
3658                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3659                         cur.undispatched();
3660                 break;
3661
3662         // insert file functions
3663         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3664         case LFUN_FILE_INSERT_PLAINTEXT:
3665                 // FIXME UNICODE
3666                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
3667                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3668                                 FileName(to_utf8(cmd.argument())));
3669                         if (tmpstr.empty())
3670                                 break;
3671                         cur.recordUndoInset(INSERT_UNDO);
3672                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3673                                 // content has been replaced,
3674                                 // so cursor might be invalid
3675                                 cur.pos() = cur.lastpos();
3676                                 cur.pit() = cur.lastpit();
3677                                 bvcur.setCursor(cur);
3678                         } else
3679                                 cur.undispatched();
3680                 }
3681                 break;
3682
3683         case LFUN_CUT:
3684                 if (cur.selIsMultiCell()) {
3685                         if (copySelection(cur)) {
3686                                 cur.recordUndoInset(DELETE_UNDO);
3687                                 cutSelection(cur);
3688                         }
3689                 } else
3690                         cell(cur.idx())->dispatch(cur, cmd);
3691                 break;
3692
3693         case LFUN_SELF_INSERT:
3694                 if (cur.selIsMultiCell()) {
3695                         cur.recordUndoInset(DELETE_UNDO);
3696                         cutSelection(cur);
3697                 }
3698                 cell(cur.idx())->dispatch(cur, cmd);
3699                 break;
3700
3701         case LFUN_CHAR_DELETE_BACKWARD:
3702         case LFUN_CHAR_DELETE_FORWARD:
3703                 if (cur.selIsMultiCell()) {
3704                         cur.recordUndoInset(DELETE_UNDO);
3705                         cutSelection(cur);
3706                 }
3707                 else
3708                         cell(cur.idx())->dispatch(cur, cmd);
3709                 break;
3710
3711         case LFUN_COPY:
3712                 if (!cur.selection())
3713                         break;
3714                 if (cur.selIsMultiCell()) {
3715                         cur.finishUndo();
3716                         copySelection(cur);
3717                 } else
3718                         cell(cur.idx())->dispatch(cur, cmd);
3719                 break;
3720
3721         case LFUN_CLIPBOARD_PASTE:
3722         case LFUN_PRIMARY_SELECTION_PASTE: {
3723                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3724                         theClipboard().getAsText() :
3725                         theSelection().get();
3726                 if (clip.empty())
3727                         break;
3728                 // pass to InsertPlaintextString, but
3729                 // only if we have multi-cell content
3730                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3731                         cur.recordUndoInset(INSERT_UNDO);
3732                         if (insertPlaintextString(cur.bv(), clip, false)) {
3733                                 // content has been replaced,
3734                                 // so cursor might be invalid
3735                                 cur.pos() = cur.lastpos();
3736                                 cur.pit() = cur.lastpit();
3737                                 bvcur.setCursor(cur);
3738                                 break;
3739                         }
3740                 }
3741                 // Let the cell handle normal text
3742                 cell(cur.idx())->dispatch(cur, cmd);
3743                 break;
3744         }
3745
3746         case LFUN_PASTE:
3747                 if (!tabularStackDirty()) {
3748                         if (!cur.selIsMultiCell())
3749                                 cell(cur.idx())->dispatch(cur, cmd);
3750                         break;
3751                 }
3752                 if (theClipboard().isInternal() ||
3753                     (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
3754                         cur.recordUndoInset(INSERT_UNDO);
3755                         pasteClipboard(cur);
3756                 }
3757                 break;
3758
3759         case LFUN_FONT_EMPH:
3760         case LFUN_FONT_BOLD:
3761         case LFUN_FONT_BOLDSYMBOL:
3762         case LFUN_FONT_ROMAN:
3763         case LFUN_FONT_NOUN:
3764         case LFUN_FONT_ITAL:
3765         case LFUN_FONT_FRAK:
3766         case LFUN_FONT_TYPEWRITER:
3767         case LFUN_FONT_SANS:
3768         case LFUN_TEXTSTYLE_APPLY:
3769         case LFUN_TEXTSTYLE_UPDATE:
3770         case LFUN_FONT_SIZE:
3771         case LFUN_FONT_UNDERLINE:
3772         case LFUN_FONT_STRIKEOUT:
3773         case LFUN_FONT_UULINE:
3774         case LFUN_FONT_UWAVE:
3775         case LFUN_LANGUAGE:
3776         case LFUN_WORD_CAPITALIZE:
3777         case LFUN_WORD_UPCASE:
3778         case LFUN_WORD_LOWCASE:
3779         case LFUN_CHARS_TRANSPOSE:
3780                 if (cur.selIsMultiCell()) {
3781                         row_type rs, re;
3782                         col_type cs, ce;
3783                         getSelection(cur, rs, re, cs, ce);
3784                         Cursor tmpcur = cur;
3785                         for (row_type i = rs; i <= re; ++i) {
3786                                 for (col_type j = cs; j <= ce; ++j) {
3787                                         // cursor follows cell:
3788                                         tmpcur.idx() = tabular.cellIndex(i, j);
3789                                         // select this cell only:
3790                                         tmpcur.pit() = 0;
3791                                         tmpcur.pos() = 0;
3792                                         tmpcur.resetAnchor();
3793                                         tmpcur.pit() = tmpcur.lastpit();
3794                                         tmpcur.pos() = tmpcur.top().lastpos();
3795                                         tmpcur.setCursor(tmpcur);
3796                                         tmpcur.setSelection();
3797                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3798                                 }
3799                         }
3800                         break;
3801                 } else {
3802                         cell(cur.idx())->dispatch(cur, cmd);
3803                         break;
3804                 }
3805
3806         case LFUN_INSET_SETTINGS:
3807                 // relay this lfun to Inset, not to the cell.
3808                 Inset::doDispatch(cur, cmd);
3809                 break;
3810
3811         default:
3812                 // we try to handle this event in the insets dispatch function.
3813                 cell(cur.idx())->dispatch(cur, cmd);
3814                 break;
3815         }
3816 }
3817
3818
3819 // function sets an object as defined in func_status.h:
3820 // states OK, Unknown, Disabled, On, Off.
3821 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3822         FuncStatus & status) const
3823 {
3824         switch (cmd.action) {
3825         case LFUN_TABULAR_FEATURE: {
3826                 int action = Tabular::LAST_ACTION;
3827                 int i = 0;
3828                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3829                         string const tmp = tabularFeature[i].feature;
3830                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3831                                 action = tabularFeature[i].action;
3832                                 break;
3833                         }
3834                 }
3835                 if (action == Tabular::LAST_ACTION) {
3836                         status.clear();
3837                         status.unknown(true);
3838                         return true;
3839                 }
3840
3841                 string const argument
3842                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3843
3844                 row_type sel_row_start = 0;
3845                 row_type sel_row_end = 0;
3846                 col_type sel_col_start = 0;
3847                 col_type sel_col_end = 0;
3848                 Tabular::ltType dummyltt;
3849                 bool flag = true;
3850
3851                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3852
3853                 switch (action) {
3854                 case Tabular::SET_PWIDTH:
3855                 case Tabular::SET_MPWIDTH:
3856                 case Tabular::SET_SPECIAL_COLUMN:
3857                 case Tabular::SET_SPECIAL_MULTI:
3858                 case Tabular::APPEND_ROW:
3859                 case Tabular::APPEND_COLUMN:
3860                 case Tabular::DELETE_ROW:
3861                 case Tabular::DELETE_COLUMN:
3862                 case Tabular::COPY_ROW:
3863                 case Tabular::COPY_COLUMN:
3864                 case Tabular::SET_TOP_SPACE:
3865                 case Tabular::SET_BOTTOM_SPACE:
3866                 case Tabular::SET_INTERLINE_SPACE:
3867                         status.clear();
3868                         return true;
3869
3870                 case Tabular::MULTICOLUMN:
3871                         // If a row is set as longtable caption, it must not be allowed
3872                         // to unset that this row is a multicolumn.
3873                         status.setEnabled(sel_row_start == sel_row_end
3874                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
3875                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3876                         break;
3877
3878                 case Tabular::SET_ALL_LINES:
3879                 case Tabular::UNSET_ALL_LINES:
3880                 case Tabular::SET_BORDER_LINES:
3881                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3882                         break;
3883
3884                 case Tabular::TOGGLE_LINE_TOP:
3885                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3886                         status.setOnOff(tabular.topLine(cur.idx()));
3887                         break;
3888
3889                 case Tabular::TOGGLE_LINE_BOTTOM:
3890                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3891                         status.setOnOff(tabular.bottomLine(cur.idx()));
3892                         break;
3893
3894                 case Tabular::TOGGLE_LINE_LEFT:
3895                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3896                         status.setOnOff(tabular.leftLine(cur.idx()));
3897                         break;
3898
3899                 case Tabular::TOGGLE_LINE_RIGHT:
3900                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3901                         status.setOnOff(tabular.rightLine(cur.idx()));
3902                         break;
3903
3904                 case Tabular::M_ALIGN_LEFT:
3905                         flag = false;
3906                 case Tabular::ALIGN_LEFT:
3907                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3908                         break;
3909
3910                 case Tabular::M_ALIGN_RIGHT:
3911                         flag = false;
3912                 case Tabular::ALIGN_RIGHT:
3913                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3914                         break;
3915
3916                 case Tabular::M_ALIGN_CENTER:
3917                         flag = false;
3918                 case Tabular::ALIGN_CENTER:
3919                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3920                         break;
3921
3922                 case Tabular::ALIGN_BLOCK:
3923                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
3924                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3925                         break;
3926
3927                 case Tabular::M_VALIGN_TOP:
3928                         flag = false;
3929                 case Tabular::VALIGN_TOP:
3930                         status.setOnOff(
3931                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3932                         break;
3933
3934                 case Tabular::M_VALIGN_BOTTOM:
3935                         flag = false;
3936                 case Tabular::VALIGN_BOTTOM:
3937                         status.setOnOff(
3938                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3939                         break;
3940
3941                 case Tabular::M_VALIGN_MIDDLE:
3942                         flag = false;
3943                 case Tabular::VALIGN_MIDDLE:
3944                         status.setOnOff(
3945                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3946                         break;
3947
3948                 case Tabular::SET_LONGTABULAR:
3949                         status.setOnOff(tabular.is_long_tabular);
3950                         break;
3951
3952                 case Tabular::UNSET_LONGTABULAR:
3953                         status.setOnOff(!tabular.is_long_tabular);
3954                         break;
3955
3956                 case Tabular::TOGGLE_ROTATE_TABULAR:
3957                 case Tabular::SET_ROTATE_TABULAR:
3958                         status.setOnOff(tabular.rotate);
3959                         break;
3960
3961                 case Tabular::TABULAR_VALIGN_TOP:
3962                         status.setOnOff(tabular.tabular_valignment 
3963                                 == Tabular::LYX_VALIGN_TOP);
3964                         break;
3965                 case Tabular::TABULAR_VALIGN_MIDDLE:
3966                         status.setOnOff(tabular.tabular_valignment 
3967                                 == Tabular::LYX_VALIGN_MIDDLE);
3968                         break;
3969                 case Tabular::TABULAR_VALIGN_BOTTOM:
3970                         status.setOnOff(tabular.tabular_valignment 
3971                                 == Tabular::LYX_VALIGN_BOTTOM);
3972                         break;
3973
3974                 case Tabular::LONGTABULAR_ALIGN_LEFT:
3975                         status.setOnOff(tabular.longtabular_alignment 
3976                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
3977                         break;
3978                 case Tabular::LONGTABULAR_ALIGN_CENTER:
3979                         status.setOnOff(tabular.longtabular_alignment 
3980                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
3981                         break;
3982                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
3983                         status.setOnOff(tabular.longtabular_alignment 
3984                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
3985                         break;
3986
3987                 case Tabular::UNSET_ROTATE_TABULAR:
3988                         status.setOnOff(!tabular.rotate);
3989                         break;
3990
3991                 case Tabular::TOGGLE_ROTATE_CELL:
3992                 case Tabular::SET_ROTATE_CELL:
3993                         status.setOnOff(!oneCellHasRotationState(false,
3994                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3995                         break;
3996
3997                 case Tabular::UNSET_ROTATE_CELL:
3998                         status.setOnOff(!oneCellHasRotationState(true,
3999                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4000                         break;
4001
4002                 case Tabular::SET_USEBOX:
4003                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4004                         break;
4005
4006                 // every row can only be one thing:
4007                 // either a footer or header or caption
4008                 case Tabular::SET_LTFIRSTHEAD:
4009                         status.setEnabled(sel_row_start == sel_row_end
4010                                 && !tabular.ltCaption(sel_row_start));
4011                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4012                         break;
4013
4014                 case Tabular::UNSET_LTFIRSTHEAD:
4015                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4016                         break;
4017
4018                 case Tabular::SET_LTHEAD:
4019                         status.setEnabled(sel_row_start == sel_row_end
4020                                 && !tabular.ltCaption(sel_row_start));
4021                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4022                         break;
4023
4024                 case Tabular::UNSET_LTHEAD:
4025                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4026                         break;
4027
4028                 case Tabular::SET_LTFOOT:
4029                         status.setEnabled(sel_row_start == sel_row_end
4030                                 && !tabular.ltCaption(sel_row_start));
4031                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4032                         break;
4033
4034                 case Tabular::UNSET_LTFOOT:
4035                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4036                         break;
4037
4038                 case Tabular::SET_LTLASTFOOT:
4039                         status.setEnabled(sel_row_start == sel_row_end
4040                                 && !tabular.ltCaption(sel_row_start));
4041                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4042                         break;
4043
4044                 case Tabular::UNSET_LTLASTFOOT:
4045                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4046                         break;
4047
4048                 case Tabular::SET_LTNEWPAGE:
4049                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4050                         break;
4051
4052                 // only one row can be the caption
4053                 case Tabular::TOGGLE_LTCAPTION:
4054                         status.setEnabled(sel_row_start == sel_row_end
4055                                 && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4056                                 && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
4057                                 && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4058                                 && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4059                                 && (!tabular.haveLTCaption()
4060                                         || tabular.ltCaption(sel_row_start)));
4061                         status.setOnOff(tabular.ltCaption(sel_row_start));
4062                         break;
4063
4064                 case Tabular::SET_BOOKTABS:
4065                         status.setOnOff(tabular.use_booktabs);
4066                         break;
4067
4068                 case Tabular::UNSET_BOOKTABS:
4069                         status.setOnOff(!tabular.use_booktabs);
4070                         break;
4071
4072                 default:
4073                         status.clear();
4074                         status.setEnabled(false);
4075                         break;
4076                 }
4077                 return true;
4078         }
4079
4080         // These are only enabled inside tabular
4081         case LFUN_CELL_BACKWARD:
4082         case LFUN_CELL_FORWARD:
4083                 status.setEnabled(true);
4084                 return true;
4085
4086         // disable these with multiple cells selected
4087         case LFUN_INSET_INSERT:
4088         case LFUN_TABULAR_INSERT:
4089         case LFUN_FLEX_INSERT:
4090         case LFUN_FLOAT_INSERT:
4091         case LFUN_FLOAT_WIDE_INSERT:
4092         case LFUN_FOOTNOTE_INSERT:
4093         case LFUN_MARGINALNOTE_INSERT:
4094         case LFUN_MATH_INSERT:
4095         case LFUN_MATH_MODE:
4096         case LFUN_MATH_MUTATE:
4097         case LFUN_MATH_DISPLAY:
4098         case LFUN_NOTE_INSERT:
4099         case LFUN_OPTIONAL_INSERT:
4100         case LFUN_BOX_INSERT:
4101         case LFUN_BRANCH_INSERT:
4102         case LFUN_PHANTOM_INSERT:
4103         case LFUN_WRAP_INSERT:
4104         case LFUN_ERT_INSERT: {
4105                 if (cur.selIsMultiCell()) {
4106                         status.setEnabled(false);
4107                         return true;
4108                 } else
4109                         return cell(cur.idx())->getStatus(cur, cmd, status);
4110         }
4111
4112         // disable in non-fixed-width cells
4113         case LFUN_NEWLINE_INSERT:
4114         case LFUN_BREAK_PARAGRAPH: {
4115                 if (tabular.getPWidth(cur.idx()).zero()) {
4116                         status.setEnabled(false);
4117                         return true;
4118                 } else
4119                         return cell(cur.idx())->getStatus(cur, cmd, status);
4120         }
4121
4122         case LFUN_NEWPAGE_INSERT:
4123                 status.setEnabled(false);
4124                 return true;
4125
4126         case LFUN_PASTE:
4127                 if (tabularStackDirty() && theClipboard().isInternal()) {
4128                         if (cur.selIsMultiCell()) {
4129                                 row_type rs, re;
4130                                 col_type cs, ce;
4131                                 getSelection(cur, rs, re, cs, ce);
4132                                 if (paste_tabular && paste_tabular->column_info.size() == ce - cs + 1
4133                                           && paste_tabular->row_info.size() == re - rs + 1)
4134                                         status.setEnabled(true);        
4135                                 else {
4136                                         status.setEnabled(false);
4137                                         status.message(_("Selection size should match clipboard content."));
4138                                 }
4139                         } else
4140                                 status.setEnabled(true);
4141                         return true;
4142                 }
4143                 return cell(cur.idx())->getStatus(cur, cmd, status);
4144
4145         case LFUN_INSET_SETTINGS:
4146                 // relay this lfun to Inset, not to the cell.
4147                 return Inset::getStatus(cur, cmd, status);
4148
4149         case LFUN_INSET_MODIFY:
4150                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
4151                         status.setEnabled(true);
4152                         return true;
4153                 }
4154                 // Fall through
4155
4156         default:
4157                 // we try to handle this event in the insets dispatch function.
4158                 return cell(cur.idx())->getStatus(cur, cmd, status);
4159         }
4160 }
4161
4162
4163 Inset::DisplayType InsetTabular::display() const
4164 {
4165                 if (tabular.is_long_tabular) {
4166                         switch (tabular.longtabular_alignment) {
4167                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4168                                 return AlignLeft;
4169                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4170                                 return AlignCenter;
4171                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4172                                 return AlignRight;
4173                         default:
4174                                 return AlignCenter;
4175                         }
4176                 } else
4177                         return Inline;
4178 }
4179
4180
4181 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
4182 {
4183         return tabular.latex(os, runparams);
4184 }
4185
4186
4187 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4188 {
4189         os << '\n'; // output table on a new line
4190         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4191         tabular.plaintext(os, runparams, dp, false, 0);
4192         return PLAINTEXT_NEWLINE;
4193 }
4194
4195
4196 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4197 {
4198         int ret = 0;
4199         Inset * master = 0;
4200
4201         // FIXME: Why not pass a proper DocIterator here?
4202 #if 0
4203         // if the table is inside a float it doesn't need the informaltable
4204         // wrapper. Search for it.
4205         for (master = owner(); master; master = master->owner())
4206                 if (master->lyxCode() == FLOAT_CODE)
4207                         break;
4208 #endif
4209
4210         if (!master) {
4211                 os << "<informaltable>";
4212                 ++ret;
4213         }
4214         ret += tabular.docbook(os, runparams);
4215         if (!master) {
4216                 os << "</informaltable>";
4217                 ++ret;
4218         }
4219         return ret;
4220 }
4221
4222
4223 void InsetTabular::validate(LaTeXFeatures & features) const
4224 {
4225         tabular.validate(features);
4226 }
4227
4228
4229 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4230 {
4231         return tabular.cellInset(idx);
4232 }
4233
4234
4235 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4236 {
4237         return tabular.cellInset(idx);
4238 }
4239
4240
4241 void InsetTabular::cursorPos(BufferView const & bv,
4242                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4243 {
4244         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4245
4246         // y offset     correction
4247         int const row = tabular.cellRow(sl.idx());
4248         for (int i = 0; i <= row; ++i) {
4249                 if (i != 0) {
4250                         y += tabular.rowAscent(i);
4251                         y += tabular.getAdditionalHeight(i);
4252                 }
4253                 if (i != row)
4254                         y += tabular.rowDescent(i);
4255         }
4256
4257         // x offset correction
4258         int const col = tabular.cellColumn(sl.idx());
4259         int idx = tabular.cellIndex(row, 0);
4260         for (int j = 0; j < col; ++j) {
4261                 if (tabular.isPartOfMultiColumn(row, j))
4262                         continue;
4263                 x += tabular.columnWidth(idx);
4264                 ++idx;
4265         }
4266         x += tabular.getBeginningOfTextInCell(idx);
4267         x += ADD_TO_TABULAR_WIDTH;
4268         x += scx_;
4269 }
4270
4271
4272 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4273 {
4274         int xx = 0;
4275         int yy = 0;
4276         Inset const & inset = *tabular.cellInset(cell);
4277         Point o = bv.coordCache().getInsets().xy(&inset);
4278         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
4279         int const xend = xbeg + tabular.columnWidth(cell);
4280         row_type const row = tabular.cellRow(cell);
4281         int const ybeg = o.y_ - tabular.rowAscent(row) -
4282                          tabular.getAdditionalHeight(row);
4283         int const yend = o.y_ + tabular.rowDescent(row);
4284
4285         if (x < xbeg)
4286                 xx = xbeg - x;
4287         else if (x > xend)
4288                 xx = x - xend;
4289
4290         if (y < ybeg)
4291                 yy = ybeg - y;
4292         else if (y > yend)
4293                 yy = y - yend;
4294
4295         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4296         //       << " ybeg=" << ybeg << " yend=" << yend
4297         //       << " xx=" << xx << " yy=" << yy
4298         //       << " dist=" << xx + yy << endl;
4299         return xx + yy;
4300 }
4301
4302
4303 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4304 {
4305         //lyxerr << "InsetTabular::editXY: " << this << endl;
4306         cur.setSelection(false);
4307         cur.push(*this);
4308         cur.idx() = getNearestCell(cur.bv(), x, y);
4309         resetPos(cur);
4310         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4311 }
4312
4313
4314 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4315 {
4316         cur.idx() = getNearestCell(cur.bv(), x, y);
4317         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4318 }
4319
4320
4321 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4322 {
4323         idx_type idx_min = 0;
4324         int dist_min = numeric_limits<int>::max();
4325         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4326                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4327                         int const d = dist(bv, i, x, y);
4328                         if (d < dist_min) {
4329                                 dist_min = d;
4330                                 idx_min = i;
4331                         }
4332                 }
4333         }
4334         return idx_min;
4335 }
4336
4337
4338 int InsetTabular::cellXPos(idx_type const cell) const
4339 {
4340         idx_type c = cell;
4341
4342         for (; !tabular.isFirstCellInRow(c); --c)
4343                 ;
4344         int lx = 0;
4345         for (; c < cell; ++c)
4346                 lx += tabular.columnWidth(c);
4347
4348         return lx;
4349 }
4350
4351
4352 void InsetTabular::resetPos(Cursor & cur) const
4353 {
4354         BufferView & bv = cur.bv();
4355         int const maxwidth = bv.workWidth();
4356
4357         int const scx_old = scx_;
4358         int const i = cur.find(this);
4359         if (i == -1) {
4360                 scx_ = 0;
4361         } else {
4362                 int const X1 = 0;
4363                 int const X2 = maxwidth;
4364                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4365                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4366                 int const x2 = x1 + tabular.columnWidth(cur[i].idx());
4367
4368                 if (x1 < X1)
4369                         scx_ = X1 + 20 - x1;
4370                 else if (x2 > X2)
4371                         scx_ = X2 - 20 - x2;
4372                 else
4373                         scx_ = 0;
4374         }
4375
4376         // only update if offset changed
4377         if (scx_ != scx_old)
4378                 cur.updateFlags(Update::Force | Update::FitCursor);
4379 }
4380
4381
4382 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4383 {
4384         if (isRightToLeft(cur)) {
4385                 if (tabular.isFirstCellInRow(cur.idx())) {
4386                         row_type const row = tabular.cellRow(cur.idx());
4387                         if (row == tabular.row_info.size() - 1)
4388                                 return;
4389                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4390                 } else {
4391                         if (cur.idx() == 0)
4392                                 return;
4393                         --cur.idx();
4394                 }
4395         } else {
4396                 if (tabular.isLastCell(cur.idx()))
4397                         return;
4398                 ++cur.idx();
4399         }
4400
4401         cur.boundary(false);
4402
4403         if (cur.selIsMultiCell()) {
4404                 cur.pit() = cur.lastpit();
4405                 cur.pos() = cur.lastpos();
4406                 resetPos(cur);
4407                 return;
4408         }
4409
4410         cur.pit() = 0;
4411         cur.pos() = 0;
4412
4413         // in visual mode, place cursor at extreme left or right
4414         
4415         switch(entry_from) {
4416
4417         case ENTRY_DIRECTION_RIGHT:
4418                 cur.posVisToRowExtremity(false /* !left */);
4419                 break;
4420         case ENTRY_DIRECTION_LEFT:
4421                 cur.posVisToRowExtremity(true /* left */);
4422                 break;
4423         case ENTRY_DIRECTION_IGNORE:
4424                 // nothing to do in this case
4425                 break;
4426
4427         }
4428
4429         resetPos(cur);
4430 }
4431
4432
4433 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4434 {
4435         if (isRightToLeft(cur)) {
4436                 if (tabular.isLastCellInRow(cur.idx())) {
4437                         row_type const row = tabular.cellRow(cur.idx());
4438                         if (row == 0)
4439                                 return;
4440                         cur.idx() = tabular.getFirstCellInRow(row);
4441                         cur.idx() = tabular.cellAbove(cur.idx());
4442                 } else {
4443                         if (tabular.isLastCell(cur.idx()))
4444                                 return;
4445                         ++cur.idx();
4446                 }
4447         } else {
4448                 if (cur.idx() == 0) // first cell
4449                         return;
4450                 --cur.idx();
4451         }
4452
4453         if (cur.selIsMultiCell()) {
4454                 cur.pit() = cur.lastpit();
4455                 cur.pos() = cur.lastpos();
4456                 resetPos(cur);
4457                 return;
4458         }
4459
4460         cur.pit() = cur.lastpit();
4461         cur.pos() = cur.lastpos();
4462
4463         // in visual mode, place cursor at extreme left or right
4464         
4465         switch(entry_from) {
4466
4467         case ENTRY_DIRECTION_RIGHT:
4468                 cur.posVisToRowExtremity(false /* !left */);
4469                 break;
4470         case ENTRY_DIRECTION_LEFT:
4471                 cur.posVisToRowExtremity(true /* left */);
4472                 break;
4473         case ENTRY_DIRECTION_IGNORE:
4474                 // nothing to do in this case
4475                 break;
4476
4477         }
4478
4479         resetPos(cur);
4480 }
4481
4482
4483 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4484 {
4485         Tabular::Feature action = Tabular::LAST_ACTION;
4486
4487         int i = 0;
4488         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4489                 string const tmp = tabularFeature[i].feature;
4490
4491                 if (tmp == what.substr(0, tmp.length())) {
4492                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4493                         //tabularFeatures[i].feature.length()))
4494                         action = tabularFeature[i].action;
4495                         break;
4496                 }
4497         }
4498         if (action == Tabular::LAST_ACTION)
4499                 return false;
4500
4501         string const val =
4502                 ltrim(what.substr(tabularFeature[i].feature.length()));
4503         tabularFeatures(cur, action, val);
4504         return true;
4505 }
4506
4507
4508 static void checkLongtableSpecial(Tabular::ltType & ltt,
4509                           string const & special, bool & flag)
4510 {
4511         if (special == "dl_above") {
4512                 ltt.topDL = flag;
4513                 ltt.set = false;
4514         } else if (special == "dl_below") {
4515                 ltt.bottomDL = flag;
4516                 ltt.set = false;
4517         } else if (special == "empty") {
4518                 ltt.empty = flag;
4519                 ltt.set = false;
4520         } else if (flag) {
4521                 ltt.empty = false;
4522                 ltt.set = true;
4523         }
4524 }
4525
4526 bool InsetTabular::oneCellHasRotationState(bool rotated,
4527                 row_type row_start, row_type row_end,
4528                 col_type col_start, col_type col_end) const {
4529
4530         for (row_type i = row_start; i <= row_end; ++i) {
4531                 for (col_type j = col_start; j <= col_end; ++j) {
4532                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4533                                 == rotated) {
4534                                 return true;
4535                         }
4536                 }
4537         }
4538         return false;
4539 }
4540
4541 void InsetTabular::tabularFeatures(Cursor & cur,
4542         Tabular::Feature feature, string const & value)
4543 {
4544         col_type sel_col_start;
4545         col_type sel_col_end;
4546         row_type sel_row_start;
4547         row_type sel_row_end;
4548         bool setLines = false;
4549         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4550         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4551
4552         switch (feature) {
4553
4554         case Tabular::M_ALIGN_LEFT:
4555         case Tabular::ALIGN_LEFT:
4556                 setAlign = LYX_ALIGN_LEFT;
4557                 break;
4558
4559         case Tabular::M_ALIGN_RIGHT:
4560         case Tabular::ALIGN_RIGHT:
4561                 setAlign = LYX_ALIGN_RIGHT;
4562                 break;
4563
4564         case Tabular::M_ALIGN_CENTER:
4565         case Tabular::ALIGN_CENTER:
4566                 setAlign = LYX_ALIGN_CENTER;
4567                 break;
4568
4569         case Tabular::ALIGN_BLOCK:
4570                 setAlign = LYX_ALIGN_BLOCK;
4571                 break;
4572
4573         case Tabular::M_VALIGN_TOP:
4574         case Tabular::VALIGN_TOP:
4575                 setVAlign = Tabular::LYX_VALIGN_TOP;
4576                 break;
4577
4578         case Tabular::M_VALIGN_BOTTOM:
4579         case Tabular::VALIGN_BOTTOM:
4580                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4581                 break;
4582
4583         case Tabular::M_VALIGN_MIDDLE:
4584         case Tabular::VALIGN_MIDDLE:
4585                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4586                 break;
4587
4588         default:
4589                 break;
4590         }
4591
4592         cur.recordUndoInset(ATOMIC_UNDO);
4593
4594         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4595         row_type const row = tabular.cellRow(cur.idx());
4596         col_type const column = tabular.cellColumn(cur.idx());
4597         bool flag = true;
4598         Tabular::ltType ltt;
4599
4600         switch (feature) {
4601
4602         case Tabular::SET_PWIDTH: {
4603                 Length const len(value);
4604                 tabular.setColumnPWidth(cur, cur.idx(), len);
4605                 if (len.zero()
4606                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4607                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4608                 break;
4609         }
4610
4611         case Tabular::SET_MPWIDTH:
4612                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4613                 break;
4614
4615         case Tabular::SET_SPECIAL_COLUMN:
4616         case Tabular::SET_SPECIAL_MULTI:
4617                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4618                 break;
4619
4620         case Tabular::APPEND_ROW:
4621                 // append the row into the tabular
4622                 tabular.appendRow(cur.idx());
4623                 break;
4624
4625         case Tabular::APPEND_COLUMN:
4626                 // append the column into the tabular
4627                 tabular.appendColumn(cur.idx());
4628                 cur.idx() = tabular.cellIndex(row, column);
4629                 break;
4630
4631         case Tabular::DELETE_ROW:
4632                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4633                         tabular.deleteRow(sel_row_start);
4634                 if (sel_row_start >= tabular.row_info.size())
4635                         --sel_row_start;
4636                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4637                 cur.pit() = 0;
4638                 cur.pos() = 0;
4639                 cur.setSelection(false);
4640                 break;
4641
4642         case Tabular::DELETE_COLUMN:
4643                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4644                         tabular.deleteColumn(sel_col_start);
4645                 if (sel_col_start >= tabular.column_info.size())
4646                         --sel_col_start;
4647                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4648                 cur.pit() = 0;
4649                 cur.pos() = 0;
4650                 cur.setSelection(false);
4651                 break;
4652
4653         case Tabular::COPY_ROW:
4654                 tabular.copyRow(row);
4655                 break;
4656
4657         case Tabular::COPY_COLUMN:
4658                 tabular.copyColumn(column);
4659                 cur.idx() = tabular.cellIndex(row, column);
4660                 break;
4661
4662         case Tabular::TOGGLE_LINE_TOP: {
4663                 bool lineSet = !tabular.topLine(cur.idx());
4664                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4665                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4666                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4667                 break;
4668         }
4669
4670         case Tabular::TOGGLE_LINE_BOTTOM: {
4671                 bool lineSet = !tabular.bottomLine(cur.idx());
4672                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4673                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4674                                 tabular.setBottomLine(tabular.cellIndex(i, j), lineSet);
4675                 break;
4676         }
4677
4678         case Tabular::TOGGLE_LINE_LEFT: {
4679                 bool lineSet = !tabular.leftLine(cur.idx());
4680                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4681                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4682                                 tabular.setLeftLine(tabular.cellIndex(i, j), lineSet);
4683                 break;
4684         }
4685
4686         case Tabular::TOGGLE_LINE_RIGHT: {
4687                 bool lineSet = !tabular.rightLine(cur.idx());
4688                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4689                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4690                                 tabular.setRightLine(tabular.cellIndex(i, j), lineSet);
4691                 break;
4692         }
4693
4694         case Tabular::M_ALIGN_LEFT:
4695         case Tabular::M_ALIGN_RIGHT:
4696         case Tabular::M_ALIGN_CENTER:
4697                 flag = false;
4698         case Tabular::ALIGN_LEFT:
4699         case Tabular::ALIGN_RIGHT:
4700         case Tabular::ALIGN_CENTER:
4701         case Tabular::ALIGN_BLOCK:
4702                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4703                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4704                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4705                 break;
4706
4707         case Tabular::M_VALIGN_TOP:
4708         case Tabular::M_VALIGN_BOTTOM:
4709         case Tabular::M_VALIGN_MIDDLE:
4710                 flag = false;
4711         case Tabular::VALIGN_TOP:
4712         case Tabular::VALIGN_BOTTOM:
4713         case Tabular::VALIGN_MIDDLE:
4714                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4715                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4716                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4717                 break;
4718
4719         case Tabular::MULTICOLUMN: {
4720                 if (!cur.selection()) {
4721                         // just multicol for one single cell
4722                         // check whether we are completely in a multicol
4723                         if (tabular.isMultiColumn(cur.idx()))
4724                                 tabular.unsetMultiColumn(cur.idx());
4725                         else
4726                                 tabular.setMultiColumn(cur.idx(), 1);
4727                         break;
4728                 }
4729                 // we have a selection so this means we just add all this
4730                 // cells to form a multicolumn cell
4731                 idx_type const s_start = cur.selBegin().idx();
4732                 idx_type const s_end = cur.selEnd().idx();
4733                 tabular.setMultiColumn(s_start, s_end - s_start + 1);
4734                 cur.idx() = s_start;
4735                 cur.pit() = 0;
4736                 cur.pos() = 0;
4737                 cur.setSelection(false);
4738                 break;
4739         }
4740
4741         case Tabular::SET_ALL_LINES:
4742                 setLines = true;
4743         case Tabular::UNSET_ALL_LINES:
4744                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4745                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4746                                 tabular.setAllLines(
4747                                         tabular.cellIndex(i,j), setLines);
4748                 break;
4749
4750         case Tabular::SET_BORDER_LINES:
4751                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4752                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
4753                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
4754                 }
4755                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
4756                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
4757                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
4758                 }
4759                 break;
4760
4761         case Tabular::SET_LONGTABULAR:
4762                 tabular.is_long_tabular = true;
4763                 break;
4764
4765         case Tabular::UNSET_LONGTABULAR:
4766                 tabular.is_long_tabular = false;
4767                 break;
4768
4769         case Tabular::SET_ROTATE_TABULAR:
4770                 tabular.rotate = true;
4771                 break;
4772
4773         case Tabular::UNSET_ROTATE_TABULAR:
4774                 tabular.rotate = false;
4775                 break;
4776
4777         case Tabular::TOGGLE_ROTATE_TABULAR:
4778                 tabular.rotate = !tabular.rotate;
4779                 break;
4780
4781         case Tabular::TABULAR_VALIGN_TOP:
4782                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
4783                 break;
4784
4785         case Tabular::TABULAR_VALIGN_MIDDLE:
4786                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
4787                 break;
4788
4789         case Tabular::TABULAR_VALIGN_BOTTOM:
4790                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
4791                 break;
4792
4793         case Tabular::LONGTABULAR_ALIGN_LEFT:
4794                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
4795                 break;
4796
4797         case Tabular::LONGTABULAR_ALIGN_CENTER:
4798                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
4799                 break;
4800
4801         case Tabular::LONGTABULAR_ALIGN_RIGHT:
4802                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
4803                 break;
4804
4805                 
4806
4807         case Tabular::SET_ROTATE_CELL:
4808                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4809                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4810                                 tabular.setRotateCell(
4811                                         tabular.cellIndex(i, j), true);
4812                 break;
4813
4814         case Tabular::UNSET_ROTATE_CELL:
4815                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4816                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4817                                 tabular.setRotateCell(tabular.cellIndex(i, j), false);
4818                 break;
4819
4820         case Tabular::TOGGLE_ROTATE_CELL:
4821                 {
4822                 bool oneNotRotated = oneCellHasRotationState(false,
4823                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4824
4825                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4826                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4827                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4828                                                                           oneNotRotated);
4829                 }
4830                 break;
4831
4832         case Tabular::SET_USEBOX: {
4833                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4834                 if (val == tabular.getUsebox(cur.idx()))
4835                         val = Tabular::BOX_NONE;
4836                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4837                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4838                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4839                 break;
4840         }
4841
4842         case Tabular::UNSET_LTFIRSTHEAD:
4843                 flag = false;
4844         case Tabular::SET_LTFIRSTHEAD:
4845                 tabular.getRowOfLTFirstHead(row, ltt);
4846                 checkLongtableSpecial(ltt, value, flag);
4847                 tabular.setLTHead(row, flag, ltt, true);
4848                 break;
4849
4850         case Tabular::UNSET_LTHEAD:
4851                 flag = false;
4852         case Tabular::SET_LTHEAD:
4853                 tabular.getRowOfLTHead(row, ltt);
4854                 checkLongtableSpecial(ltt, value, flag);
4855                 tabular.setLTHead(row, flag, ltt, false);
4856                 break;
4857
4858         case Tabular::UNSET_LTFOOT:
4859                 flag = false;
4860         case Tabular::SET_LTFOOT:
4861                 tabular.getRowOfLTFoot(row, ltt);
4862                 checkLongtableSpecial(ltt, value, flag);
4863                 tabular.setLTFoot(row, flag, ltt, false);
4864                 break;
4865
4866         case Tabular::UNSET_LTLASTFOOT:
4867                 flag = false;
4868         case Tabular::SET_LTLASTFOOT:
4869                 tabular.getRowOfLTLastFoot(row, ltt);
4870                 checkLongtableSpecial(ltt, value, flag);
4871                 tabular.setLTFoot(row, flag, ltt, true);
4872                 break;
4873
4874         case Tabular::SET_LTNEWPAGE:
4875                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4876                 break;
4877
4878         case Tabular::TOGGLE_LTCAPTION: {
4879                 bool set = !tabular.ltCaption(row);
4880                 cur.idx() = tabular.setLTCaption(row, set);
4881                 cur.pit() = 0;
4882                 cur.pos() = 0;
4883                 cur.setSelection(false);
4884                 // When a row is set as caption, then also insert a caption. Otherwise
4885                 // the LaTeX output is broken, when the user doesn't add a caption.
4886                 if (set)
4887                         lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
4888                 break;
4889         }
4890
4891         case Tabular::SET_BOOKTABS:
4892                 tabular.use_booktabs = true;
4893                 break;
4894
4895         case Tabular::UNSET_BOOKTABS:
4896                 tabular.use_booktabs = false;
4897                 break;
4898
4899         case Tabular::SET_TOP_SPACE: {
4900                 Length len;
4901                 if (value == "default")
4902                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4903                                 tabular.row_info[i].top_space_default = true;
4904                 else if (isValidLength(value, &len))
4905                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4906                                 tabular.row_info[i].top_space_default = false;
4907                                 tabular.row_info[i].top_space = len;
4908                         }
4909                 else
4910                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4911                                 tabular.row_info[i].top_space_default = false;
4912                                 tabular.row_info[i].top_space = len;
4913                         }
4914                 break;
4915         }
4916
4917         case Tabular::SET_BOTTOM_SPACE: {
4918                 Length len;
4919                 if (value == "default")
4920                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4921                                 tabular.row_info[i].bottom_space_default = true;
4922                 else if (isValidLength(value, &len))
4923                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4924                                 tabular.row_info[i].bottom_space_default = false;
4925                                 tabular.row_info[i].bottom_space = len;
4926                         }
4927                 else
4928                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4929                                 tabular.row_info[i].bottom_space_default = false;
4930                                 tabular.row_info[i].bottom_space = len;
4931                         }
4932                 break;
4933         }
4934
4935         case Tabular::SET_INTERLINE_SPACE: {
4936                 Length len;
4937                 if (value == "default")
4938                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4939                                 tabular.row_info[i].interline_space_default = true;
4940                 else if (isValidLength(value, &len))
4941                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4942                                 tabular.row_info[i].interline_space_default = false;
4943                                 tabular.row_info[i].interline_space = len;
4944                         }
4945                 else
4946                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4947                                 tabular.row_info[i].interline_space_default = false;
4948                                 tabular.row_info[i].interline_space = len;
4949                         }
4950                 break;
4951         }
4952
4953         // dummy stuff just to avoid warnings
4954         case Tabular::LAST_ACTION:
4955                 break;
4956         }
4957 }
4958
4959
4960 bool InsetTabular::showInsetDialog(BufferView * bv) const
4961 {
4962         bv->showDialog("tabular", params2string(*this),
4963                 const_cast<InsetTabular *>(this));
4964         return true;
4965 }
4966
4967
4968 void InsetTabular::openLayoutDialog(BufferView * bv) const
4969 {
4970         bv->showDialog("tabular", params2string(*this),
4971                 const_cast<InsetTabular *>(this));
4972 }
4973
4974
4975 bool InsetTabular::copySelection(Cursor & cur)
4976 {
4977         if (!cur.selection())
4978                 return false;
4979
4980         row_type rs, re;
4981         col_type cs, ce;
4982         getSelection(cur, rs, re, cs, ce);
4983
4984         paste_tabular.reset(new Tabular(tabular));
4985
4986         for (row_type i = 0; i < rs; ++i)
4987                 paste_tabular->deleteRow(0);
4988
4989         row_type const rows = re - rs + 1;
4990         while (paste_tabular->row_info.size() > rows)
4991                 paste_tabular->deleteRow(rows);
4992
4993         for (col_type i = 0; i < cs; ++i)
4994                 paste_tabular->deleteColumn(0);
4995
4996         col_type const columns = ce - cs + 1;
4997         while (paste_tabular->column_info.size() > columns)
4998                 paste_tabular->deleteColumn(columns);
4999
5000         paste_tabular->setBuffer(tabular.buffer());
5001
5002         odocstringstream os;
5003         OutputParams const runparams(0);
5004         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5005         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5006         cap::copySelection(cur, os.str());
5007
5008         // mark tabular stack dirty
5009         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5010         // when we (hopefully) have a one-for-all paste mechanism.
5011         // This must be called after cap::copySelection.
5012         dirtyTabularStack(true);
5013
5014         return true;
5015 }
5016
5017
5018 bool InsetTabular::pasteClipboard(Cursor & cur)
5019 {
5020         if (!paste_tabular)
5021                 return false;
5022         col_type actcol = tabular.cellColumn(cur.idx());
5023         row_type actrow = tabular.cellRow(cur.idx());
5024
5025         if (cur.selIsMultiCell()) {
5026                 row_type re;
5027                 col_type ce;
5028                 getSelection(cur, actrow, re, actcol, ce);
5029         }
5030
5031         for (row_type r1 = 0, r2 = actrow;
5032              r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
5033              ++r1, ++r2) {
5034                 for (col_type c1 = 0, c2 = actcol;
5035                     c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
5036                     ++c1, ++c2) {
5037                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5038                               tabular.isPartOfMultiColumn(r2, c2))
5039                                 continue;
5040                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5041                                 --c2;
5042                                 continue;
5043                         }
5044                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5045                                 --c1;
5046                                 continue;
5047                         }
5048                         shared_ptr<InsetTableCell> inset(
5049                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5050                         tabular.setCellInset(r2, c2, inset);
5051                         // FIXME: change tracking (MG)
5052                         inset->setChange(Change(buffer().params().trackChanges ?
5053                                                 Change::INSERTED : Change::UNCHANGED));
5054                         cur.pos() = 0;
5055                 }
5056         }
5057         return true;
5058 }
5059
5060
5061 void InsetTabular::cutSelection(Cursor & cur)
5062 {
5063         if (!cur.selection())
5064                 return;
5065
5066         row_type rs, re;
5067         col_type cs, ce;
5068         getSelection(cur, rs, re, cs, ce);
5069         for (row_type i = rs; i <= re; ++i) {
5070                 for (col_type j = cs; j <= ce; ++j) {
5071                         shared_ptr<InsetTableCell> t
5072                                 = cell(tabular.cellIndex(i, j));
5073                         if (buffer().params().trackChanges)
5074                                 // FIXME: Change tracking (MG)
5075                                 t->setChange(Change(Change::DELETED));
5076                         else
5077                                 t->clear();
5078                 }
5079         }
5080
5081         // cursor position might be invalid now
5082         if (cur.pit() > cur.lastpit())
5083                 cur.pit() = cur.lastpit();
5084         if (cur.pos() > cur.lastpos())
5085                 cur.pos() = cur.lastpos();
5086         cur.clearSelection();
5087 }
5088
5089
5090 bool InsetTabular::isRightToLeft(Cursor & cur) const
5091 {
5092         LASSERT(cur.depth() > 1, /**/);
5093         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5094         pos_type const parentpos = cur[cur.depth() - 2].pos();
5095         return parentpar.getFontSettings(buffer().params(),
5096                                          parentpos).language()->rightToLeft();
5097 }
5098
5099 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5100                                  bool intoInsets)
5101 {
5102         LASSERT(stidx <= enidx, return docstring());
5103         docstring retval;
5104         col_type const col1 = tabular.cellColumn(stidx);
5105         col_type const col2 = tabular.cellColumn(enidx);
5106         row_type const row1 = tabular.cellRow(stidx);
5107         row_type const row2 = tabular.cellRow(enidx);
5108         bool first = true;
5109         for (col_type col = col1; col <= col2; col++)
5110                 for (row_type row = row1; row <= row2; row++) {
5111                         if (!first)
5112                                 retval += "\n";
5113                         else
5114                                 first = false;
5115                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5116                 }
5117         return retval;
5118 }
5119
5120
5121 void InsetTabular::getSelection(Cursor & cur,
5122         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5123 {
5124         CursorSlice const & beg = cur.selBegin();
5125         CursorSlice const & end = cur.selEnd();
5126         cs = tabular.cellColumn(beg.idx());
5127         ce = tabular.cellColumn(end.idx());
5128         if (cs > ce) {
5129                 ce = cs;
5130                 cs = tabular.cellColumn(end.idx());
5131         } else {
5132                 ce = tabular.cellRightColumn(end.idx());
5133         }
5134
5135         rs = tabular.cellRow(beg.idx());
5136         re = tabular.cellRow(end.idx());
5137         if (rs > re)
5138                 swap(rs, re);
5139 }
5140
5141
5142 Text * InsetTabular::getText(int idx) const
5143 {
5144         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5145 }
5146
5147
5148 void InsetTabular::setChange(Change const & change)
5149 {
5150         for (idx_type idx = 0; idx < nargs(); ++idx)
5151                 cell(idx)->setChange(change);
5152 }
5153
5154
5155 void InsetTabular::acceptChanges(BufferParams const & bparams)
5156 {
5157         for (idx_type idx = 0; idx < nargs(); ++idx)
5158                 cell(idx)->acceptChanges(bparams);
5159 }
5160
5161
5162 void InsetTabular::rejectChanges(BufferParams const & bparams)
5163 {
5164         for (idx_type idx = 0; idx < nargs(); ++idx)
5165                 cell(idx)->rejectChanges(bparams);
5166 }
5167
5168
5169 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5170 {
5171         return tabular.getPWidth(cell).zero();
5172 }
5173
5174
5175 bool InsetTabular::forcePlainLayout(idx_type cell) const
5176 {
5177         return !tabular.getPWidth(cell).zero();
5178 }
5179
5180
5181 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5182                                      bool usePaste)
5183 {
5184         if (buf.length() <= 0)
5185                 return true;
5186
5187         col_type cols = 1;
5188         row_type rows = 1;
5189         col_type maxCols = 1;
5190         size_t const len = buf.length();
5191         size_t p = 0;
5192
5193         while (p < len &&
5194                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5195                 switch (buf[p]) {
5196                 case '\t':
5197                         ++cols;
5198                         break;
5199                 case '\n':
5200                         if (p + 1 < len)
5201                                 ++rows;
5202                         maxCols = max(cols, maxCols);
5203                         cols = 1;
5204                         break;
5205                 }
5206                 ++p;
5207         }
5208         maxCols = max(cols, maxCols);
5209         Tabular * loctab;
5210         idx_type cell = 0;
5211         col_type ocol = 0;
5212         row_type row = 0;
5213         if (usePaste) {
5214                 paste_tabular.reset(new Tabular(buffer(), rows, maxCols));
5215                 loctab = paste_tabular.get();
5216                 cols = 0;
5217                 dirtyTabularStack(true);
5218         } else {
5219                 loctab = &tabular;
5220                 cell = bv.cursor().idx();
5221                 ocol = tabular.cellColumn(cell);
5222                 row = tabular.cellRow(cell);
5223         }
5224
5225         size_t op = 0;
5226         idx_type const cells = loctab->numberofcells;
5227         p = 0;
5228         cols = ocol;
5229         rows = loctab->row_info.size();
5230         col_type const columns = loctab->column_info.size();
5231
5232         while (cell < cells && p < len && row < rows &&
5233                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
5234         {
5235                 if (p >= len)
5236                         break;
5237                 switch (buf[p]) {
5238                 case '\t':
5239                         // we can only set this if we are not too far right
5240                         if (cols < columns) {
5241                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5242                                 Font const font = bv.textMetrics(&inset->text()).
5243                                         displayFont(0, 0);
5244                                 inset->setText(buf.substr(op, p - op), font,
5245                                                buffer().params().trackChanges);
5246                                 ++cols;
5247                                 ++cell;
5248                         }
5249                         break;
5250                 case '\n':
5251                         // we can only set this if we are not too far right
5252                         if (cols < columns) {
5253                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
5254                                 Font const font = bv.textMetrics(&inset->text()).
5255                                         displayFont(0, 0);
5256                                 inset->setText(buf.substr(op, p - op), font,
5257                                                buffer().params().trackChanges);
5258                         }
5259                         cols = ocol;
5260                         ++row;
5261                         if (row < rows)
5262                                 cell = loctab->cellIndex(row, cols);
5263                         break;
5264                 }
5265                 ++p;
5266                 op = p;
5267         }
5268         // check for the last cell if there is no trailing '\n'
5269         if (cell < cells && op < len) {
5270                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5271                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
5272                 inset->setText(buf.substr(op, len - op), font,
5273                         buffer().params().trackChanges);
5274         }
5275         return true;
5276 }
5277
5278
5279 void InsetTabular::addPreview(PreviewLoader & loader) const
5280 {
5281         row_type const rows = tabular.row_info.size();
5282         col_type const columns = tabular.column_info.size();
5283         for (row_type i = 0; i < rows; ++i) {
5284                 for (col_type j = 0; j < columns; ++j)
5285                         tabular.cellInset(i, j)->addPreview(loader);
5286         }
5287 }
5288
5289
5290 bool InsetTabular::completionSupported(Cursor const & cur) const
5291 {
5292         Cursor const & bvCur = cur.bv().cursor();
5293         if (&bvCur.inset() != this)
5294                 return false;
5295         return cur.text()->completionSupported(cur);
5296 }
5297
5298
5299 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
5300 {
5301         return completionSupported(cur);
5302 }
5303
5304
5305 bool InsetTabular::automaticInlineCompletion() const
5306 {
5307         return lyxrc.completion_inline_text;
5308 }
5309
5310
5311 bool InsetTabular::automaticPopupCompletion() const
5312 {
5313         return lyxrc.completion_popup_text;
5314 }
5315
5316
5317 bool InsetTabular::showCompletionCursor() const
5318 {
5319         return lyxrc.completion_cursor_text;
5320 }
5321
5322
5323 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
5324 {
5325         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
5326 }
5327
5328
5329 docstring InsetTabular::completionPrefix(Cursor const & cur) const
5330 {
5331         if (!completionSupported(cur))
5332                 return docstring();
5333         return cur.text()->completionPrefix(cur);
5334 }
5335
5336
5337 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
5338 {
5339         if (!completionSupported(cur))
5340                 return false;
5341
5342         return cur.text()->insertCompletion(cur, s, finished);
5343 }
5344
5345
5346 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
5347                                     Dimension & dim) const
5348 {
5349         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
5350         tm.completionPosAndDim(cur, x, y, dim);
5351 }
5352
5353
5354 void InsetTabular::string2params(string const & in, InsetTabular & inset)
5355 {
5356         istringstream data(in);
5357         Lexer lex;
5358         lex.setStream(data);
5359
5360         if (in.empty())
5361                 return;
5362
5363         string token;
5364         lex >> token;
5365         if (!lex || token != "tabular") {
5366                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
5367                 return;
5368         }
5369
5370         // This is part of the inset proper that is usually swallowed
5371         // by Buffer::readInset
5372         lex >> token;
5373         if (!lex || token != "Tabular") {
5374                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
5375                 return;
5376         }
5377
5378         inset.read(lex);
5379 }
5380
5381
5382 string InsetTabular::params2string(InsetTabular const & inset)
5383 {
5384         ostringstream data;
5385         data << "tabular" << ' ';
5386         inset.write(data);
5387         data << "\\end_inset\n";
5388         return data.str();
5389 }
5390
5391
5392 } // namespace lyx