]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
Fix bug #6158: Crash when entering math in tabular.
[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  * \author Uwe Stöhr
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "InsetTabular.h"
22
23 #include "buffer_funcs.h"
24 #include "Buffer.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "CoordCache.h"
28 #include "Counters.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "DispatchResult.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
34 #include "Language.h"
35 #include "LaTeXFeatures.h"
36 #include "Lexer.h"
37 #include "LyXFunc.h"
38 #include "LyXRC.h"
39 #include "MetricsInfo.h"
40 #include "OutputParams.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(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            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1331            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1332            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1333            << write_attribute("headTopDL", endhead.topDL)
1334            << write_attribute("headBottomDL", endhead.bottomDL)
1335            << write_attribute("footTopDL", endfoot.topDL)
1336            << write_attribute("footBottomDL", endfoot.bottomDL)
1337            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1338            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1339            << write_attribute("lastFootEmpty", endlastfoot.empty);
1340         // longtables cannot be aligned vertically
1341         if (!is_long_tabular)
1342            os << write_attribute("tabularvalignment", tabular_valignment);
1343         if (is_long_tabular)
1344            os << write_attribute("longtabularalignment",
1345                                  longtabular_alignment);
1346         os << ">\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 before 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         if (row_info[i].caption && !endfirsthead.empty && !haveLTFirstHead())
2311                 // if no first header and no empty first header is used,
2312                 // the caption needs to be terminated by \endfirsthead
2313                 // (bug 6057)
2314                 os << "\\endfirsthead";
2315         else
2316                 os << "\\tabularnewline";
2317         if (row_info[i].bottom_space_default) {
2318                 if (use_booktabs)
2319                         os << "\\addlinespace";
2320                 else
2321                         os << "[\\doublerulesep]";
2322         } else if (!row_info[i].bottom_space.zero()) {
2323                 if (use_booktabs)
2324                         os << "\\addlinespace";
2325                 os << '['
2326                    << from_ascii(row_info[i].bottom_space.asLatexString())
2327                    << ']';
2328         }
2329         os << '\n';
2330         ++ret;
2331
2332         //output the bottom line
2333         ret += TeXBottomHLine(os, i, lang);
2334
2335         if (row_info[i].interline_space_default) {
2336                 if (use_booktabs)
2337                         os << "\\addlinespace\n";
2338                 else
2339                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2340                 ++ret;
2341         } else if (!row_info[i].interline_space.zero()) {
2342                 if (use_booktabs)
2343                         os << "\\addlinespace["
2344                            << from_ascii(row_info[i].interline_space.asLatexString())
2345                            << "]\n";
2346                 else
2347                         os << "\\noalign{\\vskip"
2348                            << from_ascii(row_info[i].interline_space.asLatexString())
2349                            << "}\n";
2350                 ++ret;
2351         }
2352         return ret;
2353 }
2354
2355
2356 int Tabular::latex(odocstream & os, OutputParams const & runparams) const
2357 {
2358         int ret = 0;
2359
2360         //+---------------------------------------------------------------------
2361         //+                      first the opening preamble                    +
2362         //+---------------------------------------------------------------------
2363
2364         if (rotate) {
2365                 os << "\\begin{sideways}\n";
2366                 ++ret;
2367         }
2368         if (is_long_tabular) {
2369                 os << "\\begin{longtable}";
2370                 switch (longtabular_alignment) {
2371                 case LYX_LONGTABULAR_ALIGN_LEFT:
2372                         os << "[l]";
2373                         break;
2374                 case LYX_LONGTABULAR_ALIGN_CENTER:
2375                         break;
2376                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2377                         os << "[r]";
2378                         break;
2379                 }
2380         } else {
2381                 os << "\\begin{tabular}";
2382                 switch (tabular_valignment) {
2383                 case LYX_VALIGN_TOP:
2384                         os << "[t]";
2385                         break;
2386                 case LYX_VALIGN_MIDDLE:
2387                         break;
2388                 case LYX_VALIGN_BOTTOM:
2389                         os << "[b]";
2390                         break;
2391                 }
2392         }
2393         
2394         os << "{";
2395
2396         for (col_type i = 0; i < column_info.size(); ++i) {
2397                 if (columnLeftLine(i))
2398                         os << '|';
2399                 if (!column_info[i].align_special.empty()) {
2400                         os << column_info[i].align_special;
2401                 } else {
2402                         if (!column_info[i].p_width.zero()) {
2403                                 switch (column_info[i].alignment) {
2404                                 case LYX_ALIGN_LEFT:
2405                                         os << ">{\\raggedright}";
2406                                         break;
2407                                 case LYX_ALIGN_RIGHT:
2408                                         os << ">{\\raggedleft}";
2409                                         break;
2410                                 case LYX_ALIGN_CENTER:
2411                                         os << ">{\\centering}";
2412                                         break;
2413                                 case LYX_ALIGN_NONE:
2414                                 case LYX_ALIGN_BLOCK:
2415                                 case LYX_ALIGN_LAYOUT:
2416                                 case LYX_ALIGN_SPECIAL:
2417                                         break;
2418                                 }
2419
2420                                 switch (column_info[i].valignment) {
2421                                 case LYX_VALIGN_TOP:
2422                                         os << 'p';
2423                                         break;
2424                                 case LYX_VALIGN_MIDDLE:
2425                                         os << 'm';
2426                                         break;
2427                                 case LYX_VALIGN_BOTTOM:
2428                                         os << 'b';
2429                                         break;
2430                         }
2431                                 os << '{'
2432                                    << from_ascii(column_info[i].p_width.asLatexString())
2433                                    << '}';
2434                         } else {
2435                                 switch (column_info[i].alignment) {
2436                                 case LYX_ALIGN_LEFT:
2437                                         os << 'l';
2438                                         break;
2439                                 case LYX_ALIGN_RIGHT:
2440                                         os << 'r';
2441                                         break;
2442                                 default:
2443                                         os << 'c';
2444                                         break;
2445                                 }
2446                         } // end if else !column_info[i].p_width
2447                 } // end if else !column_info[i].align_special
2448                 if (columnRightLine(i))
2449                         os << '|';
2450         }
2451         os << "}\n";
2452         ++ret;
2453
2454         ret += TeXLongtableHeaderFooter(os, runparams);
2455
2456         //+---------------------------------------------------------------------
2457         //+                      the single row and columns (cells)            +
2458         //+---------------------------------------------------------------------
2459
2460         for (row_type i = 0; i < row_info.size(); ++i) {
2461                 if (isValidRow(i)) {
2462                         ret += TeXRow(os, i, runparams);
2463                         if (is_long_tabular && row_info[i].newpage) {
2464                                 os << "\\newpage\n";
2465                                 ++ret;
2466                         }
2467                 }
2468         }
2469
2470         //+---------------------------------------------------------------------
2471         //+                      the closing of the tabular                    +
2472         //+---------------------------------------------------------------------
2473
2474         if (is_long_tabular)
2475                 os << "\\end{longtable}";
2476         else
2477                 os << "\\end{tabular}";
2478         if (rotate) {
2479                 os << "\n\\end{sideways}";
2480                 ++ret;
2481         }
2482
2483         return ret;
2484 }
2485
2486
2487 int Tabular::docbookRow(odocstream & os, row_type row,
2488                            OutputParams const & runparams) const
2489 {
2490         int ret = 0;
2491         idx_type cell = getFirstCellInRow(row);
2492
2493         os << "<row>\n";
2494         for (col_type j = 0; j < column_info.size(); ++j) {
2495                 if (isPartOfMultiColumn(row, j))
2496                         continue;
2497
2498                 os << "<entry align=\"";
2499                 switch (getAlignment(cell)) {
2500                 case LYX_ALIGN_LEFT:
2501                         os << "left";
2502                         break;
2503                 case LYX_ALIGN_RIGHT:
2504                         os << "right";
2505                         break;
2506                 default:
2507                         os << "center";
2508                         break;
2509                 }
2510
2511                 os << "\" valign=\"";
2512                 switch (getVAlignment(cell)) {
2513                 case LYX_VALIGN_TOP:
2514                         os << "top";
2515                         break;
2516                 case LYX_VALIGN_BOTTOM:
2517                         os << "bottom";
2518                         break;
2519                 case LYX_VALIGN_MIDDLE:
2520                         os << "middle";
2521                 }
2522                 os << '"';
2523
2524                 if (isMultiColumn(cell)) {
2525                         os << " namest=\"col" << j << "\" ";
2526                         os << "nameend=\"col" << j + columnSpan(cell) - 1<< '"';
2527                 }
2528
2529                 os << '>';
2530                 ret += cellInset(cell)->docbook(os, runparams);
2531                 os << "</entry>\n";
2532                 ++cell;
2533         }
2534         os << "</row>\n";
2535         return ret;
2536 }
2537
2538
2539 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2540 {
2541         int ret = 0;
2542
2543         //+---------------------------------------------------------------------
2544         //+                      first the opening preamble                    +
2545         //+---------------------------------------------------------------------
2546
2547         os << "<tgroup cols=\"" << column_info.size()
2548            << "\" colsep=\"1\" rowsep=\"1\">\n";
2549
2550         for (col_type i = 0; i < column_info.size(); ++i) {
2551                 os << "<colspec colname=\"col" << i << "\" align=\"";
2552                 switch (column_info[i].alignment) {
2553                 case LYX_ALIGN_LEFT:
2554                         os << "left";
2555                         break;
2556                 case LYX_ALIGN_RIGHT:
2557                         os << "right";
2558                         break;
2559                 default:
2560                         os << "center";
2561                         break;
2562                 }
2563                 os << '"';
2564                 if (runparams.flavor == OutputParams::XML)
2565                         os << '/';
2566                 os << ">\n";
2567                 ++ret;
2568         }
2569
2570         //+---------------------------------------------------------------------
2571         //+                      Long Tabular case                             +
2572         //+---------------------------------------------------------------------
2573
2574         // output caption info
2575         if (haveLTCaption()) {
2576                 os << "<caption>\n";
2577                 ++ret;
2578                 for (row_type i = 0; i < row_info.size(); ++i) {
2579                         if (row_info[i].caption) {
2580                                 ret += docbookRow(os, i, runparams);
2581                         }
2582                 }
2583                 os << "</caption>\n";
2584                 ++ret;
2585         }
2586         // output header info
2587         if (haveLTHead() || haveLTFirstHead()) {
2588                 os << "<thead>\n";
2589                 ++ret;
2590                 for (row_type i = 0; i < row_info.size(); ++i) {
2591                         if (row_info[i].endhead || row_info[i].endfirsthead) {
2592                                 ret += docbookRow(os, i, runparams);
2593                         }
2594                 }
2595                 os << "</thead>\n";
2596                 ++ret;
2597         }
2598         // output footer info
2599         if (haveLTFoot() || haveLTLastFoot()) {
2600                 os << "<tfoot>\n";
2601                 ++ret;
2602                 for (row_type i = 0; i < row_info.size(); ++i) {
2603                         if (row_info[i].endfoot || row_info[i].endlastfoot) {
2604                                 ret += docbookRow(os, i, runparams);
2605                         }
2606                 }
2607                 os << "</tfoot>\n";
2608                 ++ret;
2609         }
2610
2611         //+---------------------------------------------------------------------
2612         //+                      the single row and columns (cells)            +
2613         //+---------------------------------------------------------------------
2614
2615         os << "<tbody>\n";
2616         ++ret;
2617         for (row_type i = 0; i < row_info.size(); ++i) {
2618                 if (isValidRow(i)) {
2619                         ret += docbookRow(os, i, runparams);
2620                 }
2621         }
2622         os << "</tbody>\n";
2623         ++ret;
2624         //+---------------------------------------------------------------------
2625         //+                      the closing of the tabular                    +
2626         //+---------------------------------------------------------------------
2627
2628         os << "</tgroup>";
2629         ++ret;
2630
2631         return ret;
2632 }
2633
2634
2635 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2636                                    vector<unsigned int> const & clen) const
2637 {
2638         idx_type const fcell = getFirstCellInRow(row);
2639         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2640         idx_type tmp = 0;
2641
2642         for (idx_type i = fcell; i < n; ++i) {
2643                 if (topLine(i)) {
2644                         ++tmp;
2645                         break;
2646                 }
2647         }
2648         if (!tmp)
2649                 return false;
2650
2651         char_type ch;
2652         for (idx_type i = fcell; i < n; ++i) {
2653                 if (topLine(i)) {
2654                         if (leftLine(i))
2655                                 os << "+-";
2656                         else
2657                                 os << "--";
2658                         ch = '-';
2659                 } else {
2660                         os << "  ";
2661                         ch = ' ';
2662                 }
2663                 col_type column = cellColumn(i);
2664                 int len = clen[column];
2665                 while (column < column_info.size() - 1
2666                        && isPartOfMultiColumn(row, ++column))
2667                         len += clen[column] + 4;
2668                 os << docstring(len, ch);
2669                 if (topLine(i)) {
2670                         if (rightLine(i))
2671                                 os << "-+";
2672                         else
2673                                 os << "--";
2674                 } else {
2675                         os << "  ";
2676                 }
2677         }
2678         os << endl;
2679         return true;
2680 }
2681
2682
2683 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2684                                       vector<unsigned int> const & clen) const
2685 {
2686         idx_type const fcell = getFirstCellInRow(row);
2687         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2688         idx_type tmp = 0;
2689
2690         for (idx_type i = fcell; i < n; ++i) {
2691                 if (bottomLine(i)) {
2692                         ++tmp;
2693                         break;
2694                 }
2695         }
2696         if (!tmp)
2697                 return false;
2698
2699         char_type ch;
2700         for (idx_type i = fcell; i < n; ++i) {
2701                 if (bottomLine(i)) {
2702                         if (leftLine(i))
2703                                 os << "+-";
2704                         else
2705                                 os << "--";
2706                         ch = '-';
2707                 } else {
2708                         os << "  ";
2709                         ch = ' ';
2710                 }
2711                 col_type column = cellColumn(i);
2712                 int len = clen[column];
2713                 while (column < column_info.size() -1
2714                        && isPartOfMultiColumn(row, ++column))
2715                         len += clen[column] + 4;
2716                 os << docstring(len, ch);
2717                 if (bottomLine(i)) {
2718                         if (rightLine(i))
2719                                 os << "-+";
2720                         else
2721                                 os << "--";
2722                 } else {
2723                         os << "  ";
2724                 }
2725         }
2726         os << endl;
2727         return true;
2728 }
2729
2730
2731 void Tabular::plaintextPrintCell(odocstream & os,
2732                                OutputParams const & runparams,
2733                                idx_type cell, row_type row, col_type column,
2734                                vector<unsigned int> const & clen,
2735                                bool onlydata) const
2736 {
2737         odocstringstream sstr;
2738         cellInset(cell)->plaintext(sstr, runparams);
2739
2740         if (onlydata) {
2741                 os << sstr.str();
2742                 return;
2743         }
2744
2745         if (leftLine(cell))
2746                 os << "| ";
2747         else
2748                 os << "  ";
2749
2750         unsigned int len1 = sstr.str().length();
2751         unsigned int len2 = clen[column];
2752         while (column < column_info.size() -1
2753                && isPartOfMultiColumn(row, ++column))
2754                 len2 += clen[column] + 4;
2755         len2 -= len1;
2756
2757         switch (getAlignment(cell)) {
2758         default:
2759         case LYX_ALIGN_LEFT:
2760                 len1 = 0;
2761                 break;
2762         case LYX_ALIGN_RIGHT:
2763                 len1 = len2;
2764                 len2 = 0;
2765                 break;
2766         case LYX_ALIGN_CENTER:
2767                 len1 = len2 / 2;
2768                 len2 -= len1;
2769                 break;
2770         }
2771
2772         os << docstring(len1, ' ') << sstr.str()
2773            << docstring(len2, ' ');
2774
2775         if (rightLine(cell))
2776                 os << " |";
2777         else
2778                 os << "  ";
2779 }
2780
2781
2782 void Tabular::plaintext(odocstream & os,
2783                            OutputParams const & runparams, int const depth,
2784                            bool onlydata, char_type delim) const
2785 {
2786         // first calculate the width of the single columns
2787         vector<unsigned int> clen(column_info.size());
2788
2789         if (!onlydata) {
2790                 // first all non (real) multicolumn cells!
2791                 for (col_type j = 0; j < column_info.size(); ++j) {
2792                         clen[j] = 0;
2793                         for (row_type i = 0; i < row_info.size(); ++i) {
2794                                 idx_type cell = cellIndex(i, j);
2795                                 if (isMultiColumnReal(cell))
2796                                         continue;
2797                                 odocstringstream sstr;
2798                                 cellInset(cell)->plaintext(sstr, runparams);
2799                                 if (clen[j] < sstr.str().length())
2800                                         clen[j] = sstr.str().length();
2801                         }
2802                 }
2803                 // then all (real) multicolumn cells!
2804                 for (col_type j = 0; j < column_info.size(); ++j) {
2805                         for (row_type i = 0; i < row_info.size(); ++i) {
2806                                 idx_type cell = cellIndex(i, j);
2807                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2808                                         continue;
2809                                 odocstringstream sstr;
2810                                 cellInset(cell)->plaintext(sstr, runparams);
2811                                 int len = int(sstr.str().length());
2812                                 idx_type const n = columnSpan(cell);
2813                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2814                                         len -= clen[k];
2815                                 if (len > int(clen[j + n - 1]))
2816                                         clen[j + n - 1] = len;
2817                         }
2818                 }
2819         }
2820         idx_type cell = 0;
2821         for (row_type i = 0; i < row_info.size(); ++i) {
2822                 if (!onlydata && plaintextTopHLine(os, i, clen))
2823                         os << docstring(depth * 2, ' ');
2824                 for (col_type j = 0; j < column_info.size(); ++j) {
2825                         if (isPartOfMultiColumn(i, j))
2826                                 continue;
2827                         if (onlydata && j > 0)
2828                                 // we don't use operator<< for single UCS4 character.
2829                                 // see explanation in docstream.h
2830                                 os.put(delim);
2831                         plaintextPrintCell(os, runparams, cell, i, j, clen, onlydata);
2832                         ++cell;
2833                 }
2834                 os << endl;
2835                 if (!onlydata) {
2836                         os << docstring(depth * 2, ' ');
2837                         if (plaintextBottomHLine(os, i, clen))
2838                                 os << docstring(depth * 2, ' ');
2839                 }
2840         }
2841 }
2842
2843
2844 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
2845 {
2846         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2847 }
2848
2849
2850 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
2851                                                col_type column) const
2852 {
2853         return cell_info[row][column].inset;
2854 }
2855
2856
2857 void Tabular::setCellInset(row_type row, col_type column,
2858                               shared_ptr<InsetTableCell> ins) const
2859 {
2860         CellData & cd = cell_info[row][column];
2861         cd.inset = ins;
2862 }
2863
2864
2865 void Tabular::validate(LaTeXFeatures & features) const
2866 {
2867         features.require("NeedTabularnewline");
2868         if (use_booktabs)
2869                 features.require("booktabs");
2870         if (is_long_tabular)
2871                 features.require("longtable");
2872         if (needRotating())
2873                 features.require("rotating");
2874         for (idx_type cell = 0; cell < numberofcells; ++cell) {
2875                 if (getVAlignment(cell) != LYX_VALIGN_TOP
2876                     || !getPWidth(cell).zero())
2877                         features.require("array");
2878                 cellInset(cell)->validate(features);
2879         }
2880 }
2881
2882
2883 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2884 {
2885         ParagraphList const & parlist = cellInset(cell)->paragraphs();
2886         ParagraphList::const_iterator cit = parlist.begin();
2887         ParagraphList::const_iterator end = parlist.end();
2888
2889         for (; cit != end; ++cit)
2890                 for (int i = 0; i < cit->size(); ++i)
2891                         if (cit->isNewline(i))
2892                                 return BOX_PARBOX;
2893
2894         return BOX_NONE;
2895 }
2896
2897
2898 /////////////////////////////////////////////////////////////////////
2899 //
2900 // InsetTableCell
2901 //
2902 /////////////////////////////////////////////////////////////////////
2903
2904 InsetTableCell::InsetTableCell(Buffer & buf)
2905         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
2906           contentAlign(LYX_ALIGN_CENTER)
2907 {}
2908
2909
2910 bool InsetTableCell::forcePlainLayout(idx_type) const
2911 {
2912         return !isFixedWidth;
2913 }
2914
2915
2916 bool InsetTableCell::allowParagraphCustomization(idx_type) const
2917 {
2918         return isFixedWidth;
2919 }
2920
2921
2922 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
2923         FuncStatus & status) const
2924 {
2925         bool enabled;
2926         switch (cmd.action) {
2927         case LFUN_LAYOUT:
2928                 enabled = !forcePlainLayout();
2929                 break;
2930         case LFUN_LAYOUT_PARAGRAPH:
2931                 enabled = allowParagraphCustomization();
2932                 break;
2933         default:
2934                 return InsetText::getStatus(cur, cmd, status);
2935         }
2936         status.setEnabled(enabled);
2937         return true;
2938 }
2939
2940 docstring InsetTableCell::asString(bool intoInsets) 
2941 {
2942         docstring retval;
2943         if (paragraphs().empty())
2944                 return retval;
2945         ParagraphList::const_iterator it = paragraphs().begin();
2946         ParagraphList::const_iterator en = paragraphs().end();
2947         bool first = true;
2948         for (; it != en; ++it) {
2949                 if (!first)
2950                         retval += "\n";
2951                 else
2952                         first = false;
2953                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
2954         }
2955         return retval;
2956 }
2957
2958
2959
2960 /////////////////////////////////////////////////////////////////////
2961 //
2962 // InsetTabular
2963 //
2964 /////////////////////////////////////////////////////////////////////
2965
2966 InsetTabular::InsetTabular(Buffer & buf, row_type rows,
2967                            col_type columns)
2968         : tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
2969         rowselect_(false), colselect_(false)
2970 {
2971         setBuffer(buf); // FIXME: remove later
2972 }
2973
2974
2975 InsetTabular::InsetTabular(InsetTabular const & tab)
2976         : Inset(tab), tabular(tab.tabular),  scx_(0)
2977 {
2978 }
2979
2980
2981 InsetTabular::~InsetTabular()
2982 {
2983         hideDialogs("tabular", this);
2984 }
2985
2986
2987 void InsetTabular::setBuffer(Buffer & buf)
2988 {
2989         tabular.setBuffer(buf);
2990         Inset::setBuffer(buf);
2991 }
2992
2993
2994 bool InsetTabular::insetAllowed(InsetCode code) const
2995 {
2996         if (code == MATHMACRO_CODE
2997                 || (code == CAPTION_CODE && !tabular.is_long_tabular))
2998                 return false;
2999
3000         return true;
3001 }
3002
3003
3004 void InsetTabular::write(ostream & os) const
3005 {
3006         os << "Tabular" << endl;
3007         tabular.write(os);
3008 }
3009
3010
3011 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
3012 {
3013         // FIXME: depending on the selection state, we could offer a different menu.
3014         return from_ascii("context-tabular");
3015 }
3016
3017
3018 void InsetTabular::read(Lexer & lex)
3019 {
3020         //bool const old_format = (lex.getString() == "\\LyXTable");
3021
3022         tabular.read(lex);
3023
3024         //if (old_format)
3025         //      return;
3026
3027         lex.next();
3028         string token = lex.getString();
3029         while (lex && token != "\\end_inset") {
3030                 lex.next();
3031                 token = lex.getString();
3032         }
3033         if (!lex)
3034                 lex.printError("Missing \\end_inset at this point. ");
3035 }
3036
3037
3038 int InsetTabular::rowFromY(Cursor & cur, int y) const
3039 {
3040         // top y coordinate of tabular
3041         int h = yo(cur.bv()) - tabular.rowAscent(0);
3042         size_t nrows = tabular.row_info.size();
3043         row_type r = 0;
3044         for (; r < nrows && y > h; ++r) {
3045                 h += tabular.rowAscent(r);
3046                 h += tabular.rowDescent(r);
3047                 h += tabular.getAdditionalHeight(r);
3048         }
3049         return r - 1;
3050 }
3051
3052
3053 int InsetTabular::columnFromX(Cursor & cur, int x) const
3054 {
3055         // left x coordinate of tabular
3056         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3057         size_t ncols = tabular.column_info.size();
3058         col_type c = 0;
3059         for (; c < ncols && x > w; ++c)
3060                 w += tabular.columnWidth(c);
3061         return c - 1;
3062 }
3063
3064
3065 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3066 {
3067         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3068         //      mi.base.textwidth << "\n";
3069         if (!mi.base.bv) {
3070                 LYXERR0("need bv");
3071                 LASSERT(false, /**/);
3072         }
3073
3074         row_type i = 0;
3075         for (idx_type cell = 0; i < tabular.row_info.size(); ++i) {
3076                 int maxAsc = 0;
3077                 int maxDesc = 0;
3078                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3079                         if (tabular.isPartOfMultiColumn(i, j))
3080                                 // Multicolumn cell, but not first one
3081                                 continue;
3082                         Dimension dim;
3083                         MetricsInfo m = mi;
3084                         Length p_width;
3085                         if (tabular.cell_info[i][j].multicolumn ==
3086                                 Tabular::CELL_BEGIN_OF_MULTICOLUMN)
3087                                 p_width = tabular.cellInfo(cell).p_width;
3088                         else
3089                                 p_width = tabular.column_info[j].p_width;
3090                         if (!p_width.zero())
3091                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3092                         tabular.cellInset(cell)->metrics(m, dim);
3093                         if (!p_width.zero())
3094                                 dim.wid = m.base.textwidth;
3095                         tabular.setCellWidth(cell, dim.wid);
3096                         maxAsc  = max(maxAsc, dim.asc);
3097                         maxDesc = max(maxDesc, dim.des);
3098                         ++cell;
3099                 }
3100                 int const top_space = tabular.row_info[i].top_space_default ?
3101                         default_line_space :
3102                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
3103                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
3104                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
3105                         default_line_space :
3106                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
3107                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
3108         }
3109         tabular.updateColumnWidths();
3110         dim.asc = tabular.rowAscent(0);
3111         dim.des = tabular.height() - dim.asc;
3112         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3113 }
3114
3115 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3116         const
3117 {
3118         if (&cur.inset() == this && cur.selection()) {
3119                 if (cur.selIsMultiCell()) {
3120                         row_type rs, re;
3121                         col_type cs, ce;
3122                         getSelection(cur, rs, re, cs, ce);
3123                         
3124                         if (col >= cs && col <= ce && row >= rs && row <= re)
3125                                 return true;
3126                 } else 
3127                         if (col == tabular.cellColumn(cur.idx()) 
3128                                 && row == tabular.cellRow(cur.idx())) {
3129                         CursorSlice const & beg = cur.selBegin();
3130                         CursorSlice const & end = cur.selEnd();
3131
3132                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3133                                   && end.pos() == end.lastpos() && beg.pos() == 0
3134                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3135                                 return true;
3136                 }
3137         }
3138         return false;
3139 }
3140
3141
3142 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3143 {
3144         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
3145         BufferView * bv = pi.base.bv;
3146         Cursor & cur = pi.base.bv->cursor();
3147
3148         // FIXME: As the full background is painted in drawSelection(),
3149         // we have no choice but to do a full repaint for the Text cells.
3150         pi.full_repaint = true;
3151
3152         resetPos(bv->cursor());
3153
3154         x += scx_;
3155         x += ADD_TO_TABULAR_WIDTH;
3156
3157         bool const original_drawing_state = pi.pain.isDrawingEnabled();
3158         bool const original_selection_state = pi.selected;
3159
3160         idx_type idx = 0;
3161         first_visible_cell = Tabular::npos;
3162         for (row_type i = 0; i < tabular.row_info.size(); ++i) {
3163                 int nx = x;
3164                 int const a = tabular.rowAscent(i);
3165                 int const d = tabular.rowDescent(i);
3166                 idx = tabular.cellIndex(i, 0);
3167                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
3168                         if (tabular.isPartOfMultiColumn(i, j))
3169                                 continue;
3170                         if (first_visible_cell == Tabular::npos)
3171                                 first_visible_cell = idx;
3172
3173                         pi.selected |= isCellSelected(cur, i, j);
3174                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
3175                         // Cache the Inset position.
3176                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
3177                         if (nx + tabular.columnWidth(idx) < 0
3178                             || nx > bv->workWidth()
3179                             || y + d < 0
3180                             || y - a > bv->workHeight()) {
3181                                 pi.pain.setDrawingEnabled(false);
3182                                 cell(idx)->draw(pi, cx, y);
3183                                 drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
3184                                 pi.pain.setDrawingEnabled(original_drawing_state);
3185                         } else {
3186                                 cell(idx)->draw(pi, cx, y);
3187                                 drawCellLines(pi.pain, nx, y, i, idx, pi.change_);
3188                         }
3189                         nx += tabular.columnWidth(idx);
3190                         ++idx;
3191                         pi.selected = original_selection_state;
3192                 }
3193
3194                 if (i + 1 < tabular.row_info.size())
3195                         y += d + tabular.rowAscent(i + 1) +
3196                                 tabular.getAdditionalHeight(i + 1);
3197         }
3198 }
3199
3200
3201 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3202 {
3203         Cursor & cur = pi.base.bv->cursor();
3204         resetPos(cur);
3205
3206         x += scx_ + ADD_TO_TABULAR_WIDTH;
3207
3208         // FIXME: it is wrong to completely paint the background
3209         // if we want to do single row painting.
3210
3211         // Paint background of current tabular
3212         int const w = tabular.width();
3213         int const h = tabular.height();
3214         int yy = y - tabular.rowAscent(0);
3215         pi.pain.fillRectangle(x, yy, w, h, pi.backgroundColor(this));
3216
3217         if (!cur.selection())
3218                 return;
3219         if (&cur.inset() != this)
3220                 return;
3221
3222         //resetPos(cur);
3223
3224         bool const full_cell_selected = isCellSelected(cur,
3225                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3226
3227         if (cur.selIsMultiCell() || full_cell_selected) {
3228                 y -= tabular.rowAscent(0);
3229                 for (row_type j = 0; j < tabular.row_info.size(); ++j) {
3230                         int const a = tabular.rowAscent(j);
3231                         int const h = a + tabular.rowDescent(j);
3232                         int xx = x;
3233                         y += tabular.getAdditionalHeight(j);
3234                         for (col_type i = 0; i < tabular.column_info.size(); ++i) {
3235                                 if (tabular.isPartOfMultiColumn(j, i))
3236                                         continue;
3237                                 idx_type const cell =
3238                                         tabular.cellIndex(j, i);
3239                                 int const w = tabular.columnWidth(cell);
3240                                 if (isCellSelected(cur, j, i))
3241                                         pi.pain.fillRectangle(xx, y, w, h, Color_selection);
3242                                 xx += w;
3243                         }
3244                         y += h;
3245                 }
3246
3247         } else {
3248                 x += cellXPos(cur.idx());
3249                 x += tabular.getBeginningOfTextInCell(cur.idx());
3250                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3251         }
3252 }
3253
3254
3255 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3256                                  row_type row, idx_type cell, Change const & change) const
3257 {
3258         int x2 = x + tabular.columnWidth(cell);
3259         bool on_off = false;
3260         Color col = Color_tabularline;
3261         Color onoffcol = Color_tabularonoffline;
3262
3263         if (change.changed()) {
3264                 col = change.color();
3265                 onoffcol = change.color();
3266         }
3267
3268         if (!tabular.topAlreadyDrawn(cell)) {
3269                 on_off = !tabular.topLine(cell);
3270                 pain.line(x, y - tabular.rowAscent(row),
3271                           x2, y -  tabular.rowAscent(row),
3272                           on_off ? onoffcol : col,
3273                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3274         }
3275         on_off = !tabular.bottomLine(cell);
3276         pain.line(x, y + tabular.rowDescent(row),
3277                   x2, y + tabular.rowDescent(row),
3278                   on_off ? onoffcol : col,
3279                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3280         if (!tabular.leftAlreadyDrawn(cell)) {
3281                 on_off = !tabular.leftLine(cell);
3282                 pain.line(x, y -  tabular.rowAscent(row),
3283                           x, y +  tabular.rowDescent(row),
3284                           on_off ? onoffcol : col,
3285                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3286         }
3287         on_off = !tabular.rightLine(cell);
3288         pain.line(x2 - tabular.getAdditionalWidth(cell),
3289                   y -  tabular.rowAscent(row),
3290                   x2 - tabular.getAdditionalWidth(cell),
3291                   y +  tabular.rowDescent(row),
3292                   on_off ? onoffcol : col,
3293                   on_off ? Painter::line_onoffdash : Painter::line_solid);
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                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
3514
3515                         // ...try to dispatch to the cell's inset.
3516                         cell(cur.idx())->dispatch(cur, cmd);
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                 } else
3707                         cell(cur.idx())->dispatch(cur, cmd);
3708                 break;
3709
3710         case LFUN_COPY:
3711                 if (!cur.selection())
3712                         break;
3713                 if (cur.selIsMultiCell()) {
3714                         cur.finishUndo();
3715                         copySelection(cur);
3716                 } else
3717                         cell(cur.idx())->dispatch(cur, cmd);
3718                 break;
3719
3720         case LFUN_CLIPBOARD_PASTE:
3721         case LFUN_PRIMARY_SELECTION_PASTE: {
3722                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3723                         theClipboard().getAsText() :
3724                         theSelection().get();
3725                 if (clip.empty())
3726                         break;
3727                 // pass to InsertPlaintextString, but
3728                 // only if we have multi-cell content
3729                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3730                         cur.recordUndoInset(INSERT_UNDO);
3731                         if (insertPlaintextString(cur.bv(), clip, false)) {
3732                                 // content has been replaced,
3733                                 // so cursor might be invalid
3734                                 cur.pos() = cur.lastpos();
3735                                 cur.pit() = cur.lastpit();
3736                                 bvcur.setCursor(cur);
3737                                 break;
3738                         }
3739                 }
3740                 // Let the cell handle normal text
3741                 cell(cur.idx())->dispatch(cur, cmd);
3742                 break;
3743         }
3744
3745         case LFUN_PASTE:
3746                 if (!tabularStackDirty()) {
3747                         if (!cur.selIsMultiCell())
3748                                 cell(cur.idx())->dispatch(cur, cmd);
3749                         break;
3750                 }
3751                 if (theClipboard().isInternal() ||
3752                     (!theClipboard().hasInternal() && theClipboard().hasLyXContents())) {
3753                         cur.recordUndoInset(INSERT_UNDO);
3754                         pasteClipboard(cur);
3755                 }
3756                 break;
3757
3758         case LFUN_FONT_EMPH:
3759         case LFUN_FONT_BOLD:
3760         case LFUN_FONT_BOLDSYMBOL:
3761         case LFUN_FONT_ROMAN:
3762         case LFUN_FONT_NOUN:
3763         case LFUN_FONT_ITAL:
3764         case LFUN_FONT_FRAK:
3765         case LFUN_FONT_TYPEWRITER:
3766         case LFUN_FONT_SANS:
3767         case LFUN_TEXTSTYLE_APPLY:
3768         case LFUN_TEXTSTYLE_UPDATE:
3769         case LFUN_FONT_SIZE:
3770         case LFUN_FONT_UNDERLINE:
3771         case LFUN_FONT_STRIKEOUT:
3772         case LFUN_FONT_UULINE:
3773         case LFUN_FONT_UWAVE:
3774         case LFUN_LANGUAGE:
3775         case LFUN_WORD_CAPITALIZE:
3776         case LFUN_WORD_UPCASE:
3777         case LFUN_WORD_LOWCASE:
3778         case LFUN_CHARS_TRANSPOSE:
3779                 if (cur.selIsMultiCell()) {
3780                         row_type rs, re;
3781                         col_type cs, ce;
3782                         getSelection(cur, rs, re, cs, ce);
3783                         Cursor tmpcur = cur;
3784                         for (row_type i = rs; i <= re; ++i) {
3785                                 for (col_type j = cs; j <= ce; ++j) {
3786                                         // cursor follows cell:
3787                                         tmpcur.idx() = tabular.cellIndex(i, j);
3788                                         // select this cell only:
3789                                         tmpcur.pit() = 0;
3790                                         tmpcur.pos() = 0;
3791                                         tmpcur.resetAnchor();
3792                                         tmpcur.pit() = tmpcur.lastpit();
3793                                         tmpcur.pos() = tmpcur.top().lastpos();
3794                                         tmpcur.setCursor(tmpcur);
3795                                         tmpcur.setSelection();
3796                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3797                                 }
3798                         }
3799                         break;
3800                 } else {
3801                         cell(cur.idx())->dispatch(cur, cmd);
3802                         break;
3803                 }
3804
3805         case LFUN_INSET_SETTINGS:
3806                 // relay this lfun to Inset, not to the cell.
3807                 Inset::doDispatch(cur, cmd);
3808                 break;
3809
3810         default:
3811                 // we try to handle this event in the insets dispatch function.
3812                 cell(cur.idx())->dispatch(cur, cmd);
3813                 break;
3814         }
3815 }
3816
3817
3818 // function sets an object as defined in func_status.h:
3819 // states OK, Unknown, Disabled, On, Off.
3820 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3821         FuncStatus & status) const
3822 {
3823         switch (cmd.action) {
3824         case LFUN_TABULAR_FEATURE: {
3825                 int action = Tabular::LAST_ACTION;
3826                 int i = 0;
3827                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3828                         string const tmp = tabularFeature[i].feature;
3829                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3830                                 action = tabularFeature[i].action;
3831                                 break;
3832                         }
3833                 }
3834                 if (action == Tabular::LAST_ACTION) {
3835                         status.clear();
3836                         status.unknown(true);
3837                         return true;
3838                 }
3839
3840                 string const argument
3841                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3842
3843                 row_type sel_row_start = 0;
3844                 row_type sel_row_end = 0;
3845                 col_type sel_col_start = 0;
3846                 col_type sel_col_end = 0;
3847                 Tabular::ltType dummyltt;
3848                 bool flag = true;
3849
3850                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3851
3852                 switch (action) {
3853                 case Tabular::SET_PWIDTH:
3854                 case Tabular::SET_MPWIDTH:
3855                 case Tabular::SET_SPECIAL_COLUMN:
3856                 case Tabular::SET_SPECIAL_MULTI:
3857                 case Tabular::APPEND_ROW:
3858                 case Tabular::APPEND_COLUMN:
3859                 case Tabular::DELETE_ROW:
3860                 case Tabular::DELETE_COLUMN:
3861                 case Tabular::COPY_ROW:
3862                 case Tabular::COPY_COLUMN:
3863                 case Tabular::SET_TOP_SPACE:
3864                 case Tabular::SET_BOTTOM_SPACE:
3865                 case Tabular::SET_INTERLINE_SPACE:
3866                         status.clear();
3867                         return true;
3868
3869                 case Tabular::MULTICOLUMN:
3870                         // If a row is set as longtable caption, it must not be allowed
3871                         // to unset that this row is a multicolumn.
3872                         status.setEnabled(sel_row_start == sel_row_end
3873                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
3874                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3875                         break;
3876
3877                 case Tabular::SET_ALL_LINES:
3878                 case Tabular::UNSET_ALL_LINES:
3879                 case Tabular::SET_BORDER_LINES:
3880                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3881                         break;
3882
3883                 case Tabular::TOGGLE_LINE_TOP:
3884                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3885                         status.setOnOff(tabular.topLine(cur.idx()));
3886                         break;
3887
3888                 case Tabular::TOGGLE_LINE_BOTTOM:
3889                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3890                         status.setOnOff(tabular.bottomLine(cur.idx()));
3891                         break;
3892
3893                 case Tabular::TOGGLE_LINE_LEFT:
3894                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3895                         status.setOnOff(tabular.leftLine(cur.idx()));
3896                         break;
3897
3898                 case Tabular::TOGGLE_LINE_RIGHT:
3899                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3900                         status.setOnOff(tabular.rightLine(cur.idx()));
3901                         break;
3902
3903                 case Tabular::M_ALIGN_LEFT:
3904                         flag = false;
3905                 case Tabular::ALIGN_LEFT:
3906                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3907                         break;
3908
3909                 case Tabular::M_ALIGN_RIGHT:
3910                         flag = false;
3911                 case Tabular::ALIGN_RIGHT:
3912                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3913                         break;
3914
3915                 case Tabular::M_ALIGN_CENTER:
3916                         flag = false;
3917                 case Tabular::ALIGN_CENTER:
3918                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3919                         break;
3920
3921                 case Tabular::ALIGN_BLOCK:
3922                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
3923                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3924                         break;
3925
3926                 case Tabular::M_VALIGN_TOP:
3927                         flag = false;
3928                 case Tabular::VALIGN_TOP:
3929                         status.setOnOff(
3930                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3931                         break;
3932
3933                 case Tabular::M_VALIGN_BOTTOM:
3934                         flag = false;
3935                 case Tabular::VALIGN_BOTTOM:
3936                         status.setOnOff(
3937                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3938                         break;
3939
3940                 case Tabular::M_VALIGN_MIDDLE:
3941                         flag = false;
3942                 case Tabular::VALIGN_MIDDLE:
3943                         status.setOnOff(
3944                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3945                         break;
3946
3947                 case Tabular::SET_LONGTABULAR:
3948                         status.setOnOff(tabular.is_long_tabular);
3949                         break;
3950
3951                 case Tabular::UNSET_LONGTABULAR:
3952                         status.setOnOff(!tabular.is_long_tabular);
3953                         break;
3954
3955                 case Tabular::TOGGLE_ROTATE_TABULAR:
3956                 case Tabular::SET_ROTATE_TABULAR:
3957                         status.setOnOff(tabular.rotate);
3958                         break;
3959
3960                 case Tabular::TABULAR_VALIGN_TOP:
3961                         status.setOnOff(tabular.tabular_valignment 
3962                                 == Tabular::LYX_VALIGN_TOP);
3963                         break;
3964                 case Tabular::TABULAR_VALIGN_MIDDLE:
3965                         status.setOnOff(tabular.tabular_valignment 
3966                                 == Tabular::LYX_VALIGN_MIDDLE);
3967                         break;
3968                 case Tabular::TABULAR_VALIGN_BOTTOM:
3969                         status.setOnOff(tabular.tabular_valignment 
3970                                 == Tabular::LYX_VALIGN_BOTTOM);
3971                         break;
3972
3973                 case Tabular::LONGTABULAR_ALIGN_LEFT:
3974                         status.setOnOff(tabular.longtabular_alignment 
3975                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
3976                         break;
3977                 case Tabular::LONGTABULAR_ALIGN_CENTER:
3978                         status.setOnOff(tabular.longtabular_alignment 
3979                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
3980                         break;
3981                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
3982                         status.setOnOff(tabular.longtabular_alignment 
3983                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
3984                         break;
3985
3986                 case Tabular::UNSET_ROTATE_TABULAR:
3987                         status.setOnOff(!tabular.rotate);
3988                         break;
3989
3990                 case Tabular::TOGGLE_ROTATE_CELL:
3991                 case Tabular::SET_ROTATE_CELL:
3992                         status.setOnOff(!oneCellHasRotationState(false,
3993                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3994                         break;
3995
3996                 case Tabular::UNSET_ROTATE_CELL:
3997                         status.setOnOff(!oneCellHasRotationState(true,
3998                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3999                         break;
4000
4001                 case Tabular::SET_USEBOX:
4002                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4003                         break;
4004
4005                 // every row can only be one thing:
4006                 // either a footer or header or caption
4007                 case Tabular::SET_LTFIRSTHEAD:
4008                         status.setEnabled(sel_row_start == sel_row_end
4009                                 && !tabular.ltCaption(sel_row_start));
4010                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4011                         break;
4012
4013                 case Tabular::UNSET_LTFIRSTHEAD:
4014                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4015                         break;
4016
4017                 case Tabular::SET_LTHEAD:
4018                         status.setEnabled(sel_row_start == sel_row_end
4019                                 && !tabular.ltCaption(sel_row_start));
4020                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4021                         break;
4022
4023                 case Tabular::UNSET_LTHEAD:
4024                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4025                         break;
4026
4027                 case Tabular::SET_LTFOOT:
4028                         status.setEnabled(sel_row_start == sel_row_end
4029                                 && !tabular.ltCaption(sel_row_start));
4030                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4031                         break;
4032
4033                 case Tabular::UNSET_LTFOOT:
4034                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4035                         break;
4036
4037                 case Tabular::SET_LTLASTFOOT:
4038                         status.setEnabled(sel_row_start == sel_row_end
4039                                 && !tabular.ltCaption(sel_row_start));
4040                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4041                         break;
4042
4043                 case Tabular::UNSET_LTLASTFOOT:
4044                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4045                         break;
4046
4047                 case Tabular::SET_LTNEWPAGE:
4048                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4049                         break;
4050
4051                 // only one row can be the caption
4052                 case Tabular::TOGGLE_LTCAPTION:
4053                         status.setEnabled(sel_row_start == sel_row_end
4054                                 && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4055                                 && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
4056                                 && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4057                                 && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4058                                 && (!tabular.haveLTCaption()
4059                                         || tabular.ltCaption(sel_row_start)));
4060                         status.setOnOff(tabular.ltCaption(sel_row_start));
4061                         break;
4062
4063                 case Tabular::SET_BOOKTABS:
4064                         status.setOnOff(tabular.use_booktabs);
4065                         break;
4066
4067                 case Tabular::UNSET_BOOKTABS:
4068                         status.setOnOff(!tabular.use_booktabs);
4069                         break;
4070
4071                 default:
4072                         status.clear();
4073                         status.setEnabled(false);
4074                         break;
4075                 }
4076                 return true;
4077         }
4078
4079         // These are only enabled inside tabular
4080         case LFUN_CELL_BACKWARD:
4081         case LFUN_CELL_FORWARD:
4082                 status.setEnabled(true);
4083                 return true;
4084
4085         // disable these with multiple cells selected
4086         case LFUN_INSET_INSERT:
4087         case LFUN_TABULAR_INSERT:
4088         case LFUN_FLEX_INSERT:
4089         case LFUN_FLOAT_INSERT:
4090         case LFUN_FLOAT_WIDE_INSERT:
4091         case LFUN_FOOTNOTE_INSERT:
4092         case LFUN_MARGINALNOTE_INSERT:
4093         case LFUN_MATH_INSERT:
4094         case LFUN_MATH_MODE:
4095         case LFUN_MATH_MUTATE:
4096         case LFUN_MATH_DISPLAY:
4097         case LFUN_NOTE_INSERT:
4098         case LFUN_OPTIONAL_INSERT:
4099         case LFUN_BOX_INSERT:
4100         case LFUN_BRANCH_INSERT:
4101         case LFUN_PHANTOM_INSERT:
4102         case LFUN_WRAP_INSERT:
4103         case LFUN_ERT_INSERT: {
4104                 if (cur.selIsMultiCell()) {
4105                         status.setEnabled(false);
4106                         return true;
4107                 } else
4108                         return cell(cur.idx())->getStatus(cur, cmd, status);
4109         }
4110
4111         // disable in non-fixed-width cells
4112         case LFUN_NEWLINE_INSERT:
4113         case LFUN_BREAK_PARAGRAPH: {
4114                 if (tabular.getPWidth(cur.idx()).zero()) {
4115                         status.setEnabled(false);
4116                         return true;
4117                 } else
4118                         return cell(cur.idx())->getStatus(cur, cmd, status);
4119         }
4120
4121         case LFUN_NEWPAGE_INSERT:
4122                 status.setEnabled(false);
4123                 return true;
4124
4125         case LFUN_PASTE:
4126                 if (tabularStackDirty() && theClipboard().isInternal()) {
4127                         if (cur.selIsMultiCell()) {
4128                                 row_type rs, re;
4129                                 col_type cs, ce;
4130                                 getSelection(cur, rs, re, cs, ce);
4131                                 if (paste_tabular && paste_tabular->column_info.size() == ce - cs + 1
4132                                           && paste_tabular->row_info.size() == re - rs + 1)
4133                                         status.setEnabled(true);        
4134                                 else {
4135                                         status.setEnabled(false);
4136                                         status.message(_("Selection size should match clipboard content."));
4137                                 }
4138                         } else
4139                                 status.setEnabled(true);
4140                         return true;
4141                 }
4142                 return cell(cur.idx())->getStatus(cur, cmd, status);
4143
4144         case LFUN_INSET_SETTINGS:
4145                 // relay this lfun to Inset, not to the cell.
4146                 return Inset::getStatus(cur, cmd, status);
4147
4148         case LFUN_INSET_MODIFY:
4149                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
4150                         status.setEnabled(true);
4151                         return true;
4152                 }
4153                 // Fall through
4154
4155         default:
4156                 // we try to handle this event in the insets dispatch function.
4157                 return cell(cur.idx())->getStatus(cur, cmd, status);
4158         }
4159 }
4160
4161
4162 Inset::DisplayType InsetTabular::display() const
4163 {
4164                 if (tabular.is_long_tabular) {
4165                         switch (tabular.longtabular_alignment) {
4166                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4167                                 return AlignLeft;
4168                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4169                                 return AlignCenter;
4170                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4171                                 return AlignRight;
4172                         default:
4173                                 return AlignCenter;
4174                         }
4175                 } else
4176                         return Inline;
4177 }
4178
4179
4180 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
4181 {
4182         return tabular.latex(os, runparams);
4183 }
4184
4185
4186 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4187 {
4188         os << '\n'; // output table on a new line
4189         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4190         tabular.plaintext(os, runparams, dp, false, 0);
4191         return PLAINTEXT_NEWLINE;
4192 }
4193
4194
4195 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4196 {
4197         int ret = 0;
4198         Inset * master = 0;
4199
4200         // FIXME: Why not pass a proper DocIterator here?
4201 #if 0
4202         // if the table is inside a float it doesn't need the informaltable
4203         // wrapper. Search for it.
4204         for (master = owner(); master; master = master->owner())
4205                 if (master->lyxCode() == FLOAT_CODE)
4206                         break;
4207 #endif
4208
4209         if (!master) {
4210                 os << "<informaltable>";
4211                 ++ret;
4212         }
4213         ret += tabular.docbook(os, runparams);
4214         if (!master) {
4215                 os << "</informaltable>";
4216                 ++ret;
4217         }
4218         return ret;
4219 }
4220
4221
4222 void InsetTabular::validate(LaTeXFeatures & features) const
4223 {
4224         tabular.validate(features);
4225 }
4226
4227
4228 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4229 {
4230         return tabular.cellInset(idx);
4231 }
4232
4233
4234 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4235 {
4236         return tabular.cellInset(idx);
4237 }
4238
4239
4240 void InsetTabular::cursorPos(BufferView const & bv,
4241                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4242 {
4243         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4244
4245         // y offset     correction
4246         int const row = tabular.cellRow(sl.idx());
4247         for (int i = 0; i <= row; ++i) {
4248                 if (i != 0) {
4249                         y += tabular.rowAscent(i);
4250                         y += tabular.getAdditionalHeight(i);
4251                 }
4252                 if (i != row)
4253                         y += tabular.rowDescent(i);
4254         }
4255
4256         // x offset correction
4257         int const col = tabular.cellColumn(sl.idx());
4258         int idx = tabular.cellIndex(row, 0);
4259         for (int j = 0; j < col; ++j) {
4260                 if (tabular.isPartOfMultiColumn(row, j))
4261                         continue;
4262                 x += tabular.columnWidth(idx);
4263                 ++idx;
4264         }
4265         x += tabular.getBeginningOfTextInCell(idx);
4266         x += ADD_TO_TABULAR_WIDTH;
4267         x += scx_;
4268 }
4269
4270
4271 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4272 {
4273         int xx = 0;
4274         int yy = 0;
4275         Inset const & inset = *tabular.cellInset(cell);
4276         Point o = bv.coordCache().getInsets().xy(&inset);
4277         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
4278         int const xend = xbeg + tabular.columnWidth(cell);
4279         row_type const row = tabular.cellRow(cell);
4280         int const ybeg = o.y_ - tabular.rowAscent(row) -
4281                          tabular.getAdditionalHeight(row);
4282         int const yend = o.y_ + tabular.rowDescent(row);
4283
4284         if (x < xbeg)
4285                 xx = xbeg - x;
4286         else if (x > xend)
4287                 xx = x - xend;
4288
4289         if (y < ybeg)
4290                 yy = ybeg - y;
4291         else if (y > yend)
4292                 yy = y - yend;
4293
4294         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4295         //       << " ybeg=" << ybeg << " yend=" << yend
4296         //       << " xx=" << xx << " yy=" << yy
4297         //       << " dist=" << xx + yy << endl;
4298         return xx + yy;
4299 }
4300
4301
4302 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4303 {
4304         //lyxerr << "InsetTabular::editXY: " << this << endl;
4305         cur.setSelection(false);
4306         cur.push(*this);
4307         cur.idx() = getNearestCell(cur.bv(), x, y);
4308         resetPos(cur);
4309         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4310 }
4311
4312
4313 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4314 {
4315         cur.idx() = getNearestCell(cur.bv(), x, y);
4316         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4317 }
4318
4319
4320 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4321 {
4322         idx_type idx_min = 0;
4323         int dist_min = numeric_limits<int>::max();
4324         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4325                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4326                         int const d = dist(bv, i, x, y);
4327                         if (d < dist_min) {
4328                                 dist_min = d;
4329                                 idx_min = i;
4330                         }
4331                 }
4332         }
4333         return idx_min;
4334 }
4335
4336
4337 int InsetTabular::cellXPos(idx_type const cell) const
4338 {
4339         idx_type c = cell;
4340
4341         for (; !tabular.isFirstCellInRow(c); --c)
4342                 ;
4343         int lx = 0;
4344         for (; c < cell; ++c)
4345                 lx += tabular.columnWidth(c);
4346
4347         return lx;
4348 }
4349
4350
4351 void InsetTabular::resetPos(Cursor & cur) const
4352 {
4353         BufferView & bv = cur.bv();
4354         int const maxwidth = bv.workWidth();
4355
4356         int const scx_old = scx_;
4357         int const i = cur.find(this);
4358         if (i == -1) {
4359                 scx_ = 0;
4360         } else {
4361                 int const X1 = 0;
4362                 int const X2 = maxwidth;
4363                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4364                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4365                 int const x2 = x1 + tabular.columnWidth(cur[i].idx());
4366
4367                 if (x1 < X1)
4368                         scx_ = X1 + 20 - x1;
4369                 else if (x2 > X2)
4370                         scx_ = X2 - 20 - x2;
4371                 else
4372                         scx_ = 0;
4373         }
4374
4375         // only update if offset changed
4376         if (scx_ != scx_old)
4377                 cur.updateFlags(Update::Force | Update::FitCursor);
4378 }
4379
4380
4381 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4382 {
4383         if (isRightToLeft(cur)) {
4384                 if (tabular.isFirstCellInRow(cur.idx())) {
4385                         row_type const row = tabular.cellRow(cur.idx());
4386                         if (row == tabular.row_info.size() - 1)
4387                                 return;
4388                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4389                 } else {
4390                         if (cur.idx() == 0)
4391                                 return;
4392                         --cur.idx();
4393                 }
4394         } else {
4395                 if (tabular.isLastCell(cur.idx()))
4396                         return;
4397                 ++cur.idx();
4398         }
4399
4400         cur.boundary(false);
4401
4402         if (cur.selIsMultiCell()) {
4403                 cur.pit() = cur.lastpit();
4404                 cur.pos() = cur.lastpos();
4405                 resetPos(cur);
4406                 return;
4407         }
4408
4409         cur.pit() = 0;
4410         cur.pos() = 0;
4411
4412         // in visual mode, place cursor at extreme left or right
4413         
4414         switch(entry_from) {
4415
4416         case ENTRY_DIRECTION_RIGHT:
4417                 cur.posVisToRowExtremity(false /* !left */);
4418                 break;
4419         case ENTRY_DIRECTION_LEFT:
4420                 cur.posVisToRowExtremity(true /* left */);
4421                 break;
4422         case ENTRY_DIRECTION_IGNORE:
4423                 // nothing to do in this case
4424                 break;
4425
4426         }
4427
4428         resetPos(cur);
4429 }
4430
4431
4432 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4433 {
4434         if (isRightToLeft(cur)) {
4435                 if (tabular.isLastCellInRow(cur.idx())) {
4436                         row_type const row = tabular.cellRow(cur.idx());
4437                         if (row == 0)
4438                                 return;
4439                         cur.idx() = tabular.getFirstCellInRow(row);
4440                         cur.idx() = tabular.cellAbove(cur.idx());
4441                 } else {
4442                         if (tabular.isLastCell(cur.idx()))
4443                                 return;
4444                         ++cur.idx();
4445                 }
4446         } else {
4447                 if (cur.idx() == 0) // first cell
4448                         return;
4449                 --cur.idx();
4450         }
4451
4452         if (cur.selIsMultiCell()) {
4453                 cur.pit() = cur.lastpit();
4454                 cur.pos() = cur.lastpos();
4455                 resetPos(cur);
4456                 return;
4457         }
4458
4459         cur.pit() = cur.lastpit();
4460         cur.pos() = cur.lastpos();
4461
4462         // in visual mode, place cursor at extreme left or right
4463         
4464         switch(entry_from) {
4465
4466         case ENTRY_DIRECTION_RIGHT:
4467                 cur.posVisToRowExtremity(false /* !left */);
4468                 break;
4469         case ENTRY_DIRECTION_LEFT:
4470                 cur.posVisToRowExtremity(true /* left */);
4471                 break;
4472         case ENTRY_DIRECTION_IGNORE:
4473                 // nothing to do in this case
4474                 break;
4475
4476         }
4477
4478         resetPos(cur);
4479 }
4480
4481
4482 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4483 {
4484         Tabular::Feature action = Tabular::LAST_ACTION;
4485
4486         int i = 0;
4487         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4488                 string const tmp = tabularFeature[i].feature;
4489
4490                 if (tmp == what.substr(0, tmp.length())) {
4491                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4492                         //tabularFeatures[i].feature.length()))
4493                         action = tabularFeature[i].action;
4494                         break;
4495                 }
4496         }
4497         if (action == Tabular::LAST_ACTION)
4498                 return false;
4499
4500         string const val =
4501                 ltrim(what.substr(tabularFeature[i].feature.length()));
4502         tabularFeatures(cur, action, val);
4503         return true;
4504 }
4505
4506
4507 static void checkLongtableSpecial(Tabular::ltType & ltt,
4508                           string const & special, bool & flag)
4509 {
4510         if (special == "dl_above") {
4511                 ltt.topDL = flag;
4512                 ltt.set = false;
4513         } else if (special == "dl_below") {
4514                 ltt.bottomDL = flag;
4515                 ltt.set = false;
4516         } else if (special == "empty") {
4517                 ltt.empty = flag;
4518                 ltt.set = false;
4519         } else if (flag) {
4520                 ltt.empty = false;
4521                 ltt.set = true;
4522         }
4523 }
4524
4525 bool InsetTabular::oneCellHasRotationState(bool rotated,
4526                 row_type row_start, row_type row_end,
4527                 col_type col_start, col_type col_end) const {
4528
4529         for (row_type i = row_start; i <= row_end; ++i) {
4530                 for (col_type j = col_start; j <= col_end; ++j) {
4531                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4532                                 == rotated) {
4533                                 return true;
4534                         }
4535                 }
4536         }
4537         return false;
4538 }
4539
4540 void InsetTabular::tabularFeatures(Cursor & cur,
4541         Tabular::Feature feature, string const & value)
4542 {
4543         col_type sel_col_start;
4544         col_type sel_col_end;
4545         row_type sel_row_start;
4546         row_type sel_row_end;
4547         bool setLines = false;
4548         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4549         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4550
4551         switch (feature) {
4552
4553         case Tabular::M_ALIGN_LEFT:
4554         case Tabular::ALIGN_LEFT:
4555                 setAlign = LYX_ALIGN_LEFT;
4556                 break;
4557
4558         case Tabular::M_ALIGN_RIGHT:
4559         case Tabular::ALIGN_RIGHT:
4560                 setAlign = LYX_ALIGN_RIGHT;
4561                 break;
4562
4563         case Tabular::M_ALIGN_CENTER:
4564         case Tabular::ALIGN_CENTER:
4565                 setAlign = LYX_ALIGN_CENTER;
4566                 break;
4567
4568         case Tabular::ALIGN_BLOCK:
4569                 setAlign = LYX_ALIGN_BLOCK;
4570                 break;
4571
4572         case Tabular::M_VALIGN_TOP:
4573         case Tabular::VALIGN_TOP:
4574                 setVAlign = Tabular::LYX_VALIGN_TOP;
4575                 break;
4576
4577         case Tabular::M_VALIGN_BOTTOM:
4578         case Tabular::VALIGN_BOTTOM:
4579                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4580                 break;
4581
4582         case Tabular::M_VALIGN_MIDDLE:
4583         case Tabular::VALIGN_MIDDLE:
4584                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4585                 break;
4586
4587         default:
4588                 break;
4589         }
4590
4591         cur.recordUndoInset(ATOMIC_UNDO);
4592
4593         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4594         row_type const row = tabular.cellRow(cur.idx());
4595         col_type const column = tabular.cellColumn(cur.idx());
4596         bool flag = true;
4597         Tabular::ltType ltt;
4598
4599         switch (feature) {
4600
4601         case Tabular::SET_PWIDTH: {
4602                 Length const len(value);
4603                 tabular.setColumnPWidth(cur, cur.idx(), len);
4604                 if (len.zero()
4605                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4606                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4607                 break;
4608         }
4609
4610         case Tabular::SET_MPWIDTH:
4611                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4612                 break;
4613
4614         case Tabular::SET_SPECIAL_COLUMN:
4615         case Tabular::SET_SPECIAL_MULTI:
4616                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4617                 break;
4618
4619         case Tabular::APPEND_ROW:
4620                 // append the row into the tabular
4621                 tabular.appendRow(cur.idx());
4622                 break;
4623
4624         case Tabular::APPEND_COLUMN:
4625                 // append the column into the tabular
4626                 tabular.appendColumn(cur.idx());
4627                 cur.idx() = tabular.cellIndex(row, column);
4628                 break;
4629
4630         case Tabular::DELETE_ROW:
4631                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4632                         tabular.deleteRow(sel_row_start);
4633                 if (sel_row_start >= tabular.row_info.size())
4634                         --sel_row_start;
4635                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4636                 cur.pit() = 0;
4637                 cur.pos() = 0;
4638                 cur.setSelection(false);
4639                 break;
4640
4641         case Tabular::DELETE_COLUMN:
4642                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4643                         tabular.deleteColumn(sel_col_start);
4644                 if (sel_col_start >= tabular.column_info.size())
4645                         --sel_col_start;
4646                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4647                 cur.pit() = 0;
4648                 cur.pos() = 0;
4649                 cur.setSelection(false);
4650                 break;
4651
4652         case Tabular::COPY_ROW:
4653                 tabular.copyRow(row);
4654                 break;
4655
4656         case Tabular::COPY_COLUMN:
4657                 tabular.copyColumn(column);
4658                 cur.idx() = tabular.cellIndex(row, column);
4659                 break;
4660
4661         case Tabular::TOGGLE_LINE_TOP: {
4662                 bool lineSet = !tabular.topLine(cur.idx());
4663                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4664                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4665                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4666                 break;
4667         }
4668
4669         case Tabular::TOGGLE_LINE_BOTTOM: {
4670                 bool lineSet = !tabular.bottomLine(cur.idx());
4671                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4672                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4673                                 tabular.setBottomLine(tabular.cellIndex(i, j), lineSet);
4674                 break;
4675         }
4676
4677         case Tabular::TOGGLE_LINE_LEFT: {
4678                 bool lineSet = !tabular.leftLine(cur.idx());
4679                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4680                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4681                                 tabular.setLeftLine(tabular.cellIndex(i, j), lineSet);
4682                 break;
4683         }
4684
4685         case Tabular::TOGGLE_LINE_RIGHT: {
4686                 bool lineSet = !tabular.rightLine(cur.idx());
4687                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4688                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4689                                 tabular.setRightLine(tabular.cellIndex(i, j), lineSet);
4690                 break;
4691         }
4692
4693         case Tabular::M_ALIGN_LEFT:
4694         case Tabular::M_ALIGN_RIGHT:
4695         case Tabular::M_ALIGN_CENTER:
4696                 flag = false;
4697         case Tabular::ALIGN_LEFT:
4698         case Tabular::ALIGN_RIGHT:
4699         case Tabular::ALIGN_CENTER:
4700         case Tabular::ALIGN_BLOCK:
4701                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4702                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4703                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4704                 break;
4705
4706         case Tabular::M_VALIGN_TOP:
4707         case Tabular::M_VALIGN_BOTTOM:
4708         case Tabular::M_VALIGN_MIDDLE:
4709                 flag = false;
4710         case Tabular::VALIGN_TOP:
4711         case Tabular::VALIGN_BOTTOM:
4712         case Tabular::VALIGN_MIDDLE:
4713                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4714                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4715                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4716                 break;
4717
4718         case Tabular::MULTICOLUMN: {
4719                 if (!cur.selection()) {
4720                         // just multicol for one single cell
4721                         // check whether we are completely in a multicol
4722                         if (tabular.isMultiColumn(cur.idx()))
4723                                 tabular.unsetMultiColumn(cur.idx());
4724                         else
4725                                 tabular.setMultiColumn(cur.idx(), 1);
4726                         break;
4727                 }
4728                 // we have a selection so this means we just add all this
4729                 // cells to form a multicolumn cell
4730                 idx_type const s_start = cur.selBegin().idx();
4731                 idx_type const s_end = cur.selEnd().idx();
4732                 tabular.setMultiColumn(s_start, s_end - s_start + 1);
4733                 cur.idx() = s_start;
4734                 cur.pit() = 0;
4735                 cur.pos() = 0;
4736                 cur.setSelection(false);
4737                 break;
4738         }
4739
4740         case Tabular::SET_ALL_LINES:
4741                 setLines = true;
4742         case Tabular::UNSET_ALL_LINES:
4743                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4744                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4745                                 tabular.setAllLines(
4746                                         tabular.cellIndex(i,j), setLines);
4747                 break;
4748
4749         case Tabular::SET_BORDER_LINES:
4750                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4751                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
4752                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
4753                 }
4754                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
4755                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
4756                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
4757                 }
4758                 break;
4759
4760         case Tabular::SET_LONGTABULAR:
4761                 tabular.is_long_tabular = true;
4762                 break;
4763
4764         case Tabular::UNSET_LONGTABULAR:
4765                 tabular.is_long_tabular = false;
4766                 break;
4767
4768         case Tabular::SET_ROTATE_TABULAR:
4769                 tabular.rotate = true;
4770                 break;
4771
4772         case Tabular::UNSET_ROTATE_TABULAR:
4773                 tabular.rotate = false;
4774                 break;
4775
4776         case Tabular::TOGGLE_ROTATE_TABULAR:
4777                 tabular.rotate = !tabular.rotate;
4778                 break;
4779
4780         case Tabular::TABULAR_VALIGN_TOP:
4781                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
4782                 break;
4783
4784         case Tabular::TABULAR_VALIGN_MIDDLE:
4785                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
4786                 break;
4787
4788         case Tabular::TABULAR_VALIGN_BOTTOM:
4789                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
4790                 break;
4791
4792         case Tabular::LONGTABULAR_ALIGN_LEFT:
4793                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
4794                 break;
4795
4796         case Tabular::LONGTABULAR_ALIGN_CENTER:
4797                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
4798                 break;
4799
4800         case Tabular::LONGTABULAR_ALIGN_RIGHT:
4801                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
4802                 break;
4803
4804                 
4805
4806         case Tabular::SET_ROTATE_CELL:
4807                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4808                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4809                                 tabular.setRotateCell(
4810                                         tabular.cellIndex(i, j), true);
4811                 break;
4812
4813         case Tabular::UNSET_ROTATE_CELL:
4814                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4815                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4816                                 tabular.setRotateCell(tabular.cellIndex(i, j), false);
4817                 break;
4818
4819         case Tabular::TOGGLE_ROTATE_CELL:
4820                 {
4821                 bool oneNotRotated = oneCellHasRotationState(false,
4822                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4823
4824                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4825                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4826                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4827                                                                           oneNotRotated);
4828                 }
4829                 break;
4830
4831         case Tabular::SET_USEBOX: {
4832                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4833                 if (val == tabular.getUsebox(cur.idx()))
4834                         val = Tabular::BOX_NONE;
4835                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4836                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4837                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4838                 break;
4839         }
4840
4841         case Tabular::UNSET_LTFIRSTHEAD:
4842                 flag = false;
4843         case Tabular::SET_LTFIRSTHEAD:
4844                 tabular.getRowOfLTFirstHead(row, ltt);
4845                 checkLongtableSpecial(ltt, value, flag);
4846                 tabular.setLTHead(row, flag, ltt, true);
4847                 break;
4848
4849         case Tabular::UNSET_LTHEAD:
4850                 flag = false;
4851         case Tabular::SET_LTHEAD:
4852                 tabular.getRowOfLTHead(row, ltt);
4853                 checkLongtableSpecial(ltt, value, flag);
4854                 tabular.setLTHead(row, flag, ltt, false);
4855                 break;
4856
4857         case Tabular::UNSET_LTFOOT:
4858                 flag = false;
4859         case Tabular::SET_LTFOOT:
4860                 tabular.getRowOfLTFoot(row, ltt);
4861                 checkLongtableSpecial(ltt, value, flag);
4862                 tabular.setLTFoot(row, flag, ltt, false);
4863                 break;
4864
4865         case Tabular::UNSET_LTLASTFOOT:
4866                 flag = false;
4867         case Tabular::SET_LTLASTFOOT:
4868                 tabular.getRowOfLTLastFoot(row, ltt);
4869                 checkLongtableSpecial(ltt, value, flag);
4870                 tabular.setLTFoot(row, flag, ltt, true);
4871                 break;
4872
4873         case Tabular::SET_LTNEWPAGE:
4874                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4875                 break;
4876
4877         case Tabular::TOGGLE_LTCAPTION: {
4878                 bool set = !tabular.ltCaption(row);
4879                 cur.idx() = tabular.setLTCaption(row, set);
4880                 cur.pit() = 0;
4881                 cur.pos() = 0;
4882                 cur.setSelection(false);
4883                 // When a row is set as caption, then also insert a caption. Otherwise
4884                 // the LaTeX output is broken, when the user doesn't add a caption.
4885                 if (set)
4886                         lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
4887                 break;
4888         }
4889
4890         case Tabular::SET_BOOKTABS:
4891                 tabular.use_booktabs = true;
4892                 break;
4893
4894         case Tabular::UNSET_BOOKTABS:
4895                 tabular.use_booktabs = false;
4896                 break;
4897
4898         case Tabular::SET_TOP_SPACE: {
4899                 Length len;
4900                 if (value == "default")
4901                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4902                                 tabular.row_info[i].top_space_default = true;
4903                 else if (isValidLength(value, &len))
4904                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4905                                 tabular.row_info[i].top_space_default = false;
4906                                 tabular.row_info[i].top_space = len;
4907                         }
4908                 else
4909                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4910                                 tabular.row_info[i].top_space_default = false;
4911                                 tabular.row_info[i].top_space = len;
4912                         }
4913                 break;
4914         }
4915
4916         case Tabular::SET_BOTTOM_SPACE: {
4917                 Length len;
4918                 if (value == "default")
4919                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4920                                 tabular.row_info[i].bottom_space_default = true;
4921                 else if (isValidLength(value, &len))
4922                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4923                                 tabular.row_info[i].bottom_space_default = false;
4924                                 tabular.row_info[i].bottom_space = len;
4925                         }
4926                 else
4927                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4928                                 tabular.row_info[i].bottom_space_default = false;
4929                                 tabular.row_info[i].bottom_space = len;
4930                         }
4931                 break;
4932         }
4933
4934         case Tabular::SET_INTERLINE_SPACE: {
4935                 Length len;
4936                 if (value == "default")
4937                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4938                                 tabular.row_info[i].interline_space_default = true;
4939                 else if (isValidLength(value, &len))
4940                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4941                                 tabular.row_info[i].interline_space_default = false;
4942                                 tabular.row_info[i].interline_space = len;
4943                         }
4944                 else
4945                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4946                                 tabular.row_info[i].interline_space_default = false;
4947                                 tabular.row_info[i].interline_space = len;
4948                         }
4949                 break;
4950         }
4951
4952         // dummy stuff just to avoid warnings
4953         case Tabular::LAST_ACTION:
4954                 break;
4955         }
4956 }
4957
4958
4959 bool InsetTabular::showInsetDialog(BufferView * bv) const
4960 {
4961         bv->showDialog("tabular", params2string(*this),
4962                 const_cast<InsetTabular *>(this));
4963         return true;
4964 }
4965
4966
4967 void InsetTabular::openLayoutDialog(BufferView * bv) const
4968 {
4969         bv->showDialog("tabular", params2string(*this),
4970                 const_cast<InsetTabular *>(this));
4971 }
4972
4973
4974 bool InsetTabular::copySelection(Cursor & cur)
4975 {
4976         if (!cur.selection())
4977                 return false;
4978
4979         row_type rs, re;
4980         col_type cs, ce;
4981         getSelection(cur, rs, re, cs, ce);
4982
4983         paste_tabular.reset(new Tabular(tabular));
4984
4985         for (row_type i = 0; i < rs; ++i)
4986                 paste_tabular->deleteRow(0);
4987
4988         row_type const rows = re - rs + 1;
4989         while (paste_tabular->row_info.size() > rows)
4990                 paste_tabular->deleteRow(rows);
4991
4992         for (col_type i = 0; i < cs; ++i)
4993                 paste_tabular->deleteColumn(0);
4994
4995         col_type const columns = ce - cs + 1;
4996         while (paste_tabular->column_info.size() > columns)
4997                 paste_tabular->deleteColumn(columns);
4998
4999         paste_tabular->setBuffer(tabular.buffer());
5000
5001         odocstringstream os;
5002         OutputParams const runparams(0);
5003         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5004         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5005         cap::copySelection(cur, os.str());
5006
5007         // mark tabular stack dirty
5008         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5009         // when we (hopefully) have a one-for-all paste mechanism.
5010         // This must be called after cap::copySelection.
5011         dirtyTabularStack(true);
5012
5013         return true;
5014 }
5015
5016
5017 bool InsetTabular::pasteClipboard(Cursor & cur)
5018 {
5019         if (!paste_tabular)
5020                 return false;
5021         col_type actcol = tabular.cellColumn(cur.idx());
5022         row_type actrow = tabular.cellRow(cur.idx());
5023
5024         if (cur.selIsMultiCell()) {
5025                 row_type re;
5026                 col_type ce;
5027                 getSelection(cur, actrow, re, actcol, ce);
5028         }
5029
5030         for (row_type r1 = 0, r2 = actrow;
5031              r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
5032              ++r1, ++r2) {
5033                 for (col_type c1 = 0, c2 = actcol;
5034                     c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
5035                     ++c1, ++c2) {
5036                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5037                               tabular.isPartOfMultiColumn(r2, c2))
5038                                 continue;
5039                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5040                                 --c2;
5041                                 continue;
5042                         }
5043                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5044                                 --c1;
5045                                 continue;
5046                         }
5047                         shared_ptr<InsetTableCell> inset(
5048                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5049                         tabular.setCellInset(r2, c2, inset);
5050                         // FIXME: change tracking (MG)
5051                         inset->setChange(Change(buffer().params().trackChanges ?
5052                                                 Change::INSERTED : Change::UNCHANGED));
5053                         cur.pos() = 0;
5054                 }
5055         }
5056         return true;
5057 }
5058
5059
5060 void InsetTabular::cutSelection(Cursor & cur)
5061 {
5062         if (!cur.selection())
5063                 return;
5064
5065         row_type rs, re;
5066         col_type cs, ce;
5067         getSelection(cur, rs, re, cs, ce);
5068         for (row_type i = rs; i <= re; ++i) {
5069                 for (col_type j = cs; j <= ce; ++j) {
5070                         shared_ptr<InsetTableCell> t
5071                                 = cell(tabular.cellIndex(i, j));
5072                         if (buffer().params().trackChanges)
5073                                 // FIXME: Change tracking (MG)
5074                                 t->setChange(Change(Change::DELETED));
5075                         else
5076                                 t->clear();
5077                 }
5078         }
5079
5080         // cursor position might be invalid now
5081         if (cur.pit() > cur.lastpit())
5082                 cur.pit() = cur.lastpit();
5083         if (cur.pos() > cur.lastpos())
5084                 cur.pos() = cur.lastpos();
5085         cur.clearSelection();
5086 }
5087
5088
5089 bool InsetTabular::isRightToLeft(Cursor & cur) const
5090 {
5091         LASSERT(cur.depth() > 1, /**/);
5092         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5093         pos_type const parentpos = cur[cur.depth() - 2].pos();
5094         return parentpar.getFontSettings(buffer().params(),
5095                                          parentpos).language()->rightToLeft();
5096 }
5097
5098 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5099                                  bool intoInsets)
5100 {
5101         LASSERT(stidx <= enidx, return docstring());
5102         docstring retval;
5103         col_type const col1 = tabular.cellColumn(stidx);
5104         col_type const col2 = tabular.cellColumn(enidx);
5105         row_type const row1 = tabular.cellRow(stidx);
5106         row_type const row2 = tabular.cellRow(enidx);
5107         bool first = true;
5108         for (col_type col = col1; col <= col2; col++)
5109                 for (row_type row = row1; row <= row2; row++) {
5110                         if (!first)
5111                                 retval += "\n";
5112                         else
5113                                 first = false;
5114                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5115                 }
5116         return retval;
5117 }
5118
5119
5120 void InsetTabular::getSelection(Cursor & cur,
5121         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5122 {
5123         CursorSlice const & beg = cur.selBegin();
5124         CursorSlice const & end = cur.selEnd();
5125         cs = tabular.cellColumn(beg.idx());
5126         ce = tabular.cellColumn(end.idx());
5127         if (cs > ce) {
5128                 ce = cs;
5129                 cs = tabular.cellColumn(end.idx());
5130         } else {
5131                 ce = tabular.cellRightColumn(end.idx());
5132         }
5133
5134         rs = tabular.cellRow(beg.idx());
5135         re = tabular.cellRow(end.idx());
5136         if (rs > re)
5137                 swap(rs, re);
5138 }
5139
5140
5141 Text * InsetTabular::getText(int idx) const
5142 {
5143         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5144 }
5145
5146
5147 void InsetTabular::setChange(Change const & change)
5148 {
5149         for (idx_type idx = 0; idx < nargs(); ++idx)
5150                 cell(idx)->setChange(change);
5151 }
5152
5153
5154 void InsetTabular::acceptChanges()
5155 {
5156         for (idx_type idx = 0; idx < nargs(); ++idx)
5157                 cell(idx)->acceptChanges();
5158 }
5159
5160
5161 void InsetTabular::rejectChanges()
5162 {
5163         for (idx_type idx = 0; idx < nargs(); ++idx)
5164                 cell(idx)->rejectChanges();
5165 }
5166
5167
5168 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5169 {
5170         return tabular.getPWidth(cell).zero();
5171 }
5172
5173
5174 bool InsetTabular::forcePlainLayout(idx_type cell) const
5175 {
5176         return !tabular.getPWidth(cell).zero();
5177 }
5178
5179
5180 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5181                                      bool usePaste)
5182 {
5183         if (buf.length() <= 0)
5184                 return true;
5185
5186         col_type cols = 1;
5187         row_type rows = 1;
5188         col_type maxCols = 1;
5189         size_t const len = buf.length();
5190         size_t p = 0;
5191
5192         while (p < len &&
5193                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5194                 switch (buf[p]) {
5195                 case '\t':
5196                         ++cols;
5197                         break;
5198                 case '\n':
5199                         if (p + 1 < len)
5200                                 ++rows;
5201                         maxCols = max(cols, maxCols);
5202                         cols = 1;
5203                         break;
5204                 }
5205                 ++p;
5206         }
5207         maxCols = max(cols, maxCols);
5208         Tabular * loctab;
5209         idx_type cell = 0;
5210         col_type ocol = 0;
5211         row_type row = 0;
5212         if (usePaste) {
5213                 paste_tabular.reset(new Tabular(buffer(), rows, maxCols));
5214                 loctab = paste_tabular.get();
5215                 cols = 0;
5216                 dirtyTabularStack(true);
5217         } else {
5218                 loctab = &tabular;
5219                 cell = bv.cursor().idx();
5220                 ocol = tabular.cellColumn(cell);
5221                 row = tabular.cellRow(cell);
5222         }
5223
5224         size_t op = 0;
5225         idx_type const cells = loctab->numberofcells;
5226         p = 0;
5227         cols = ocol;
5228         rows = loctab->row_info.size();
5229         col_type const columns = loctab->column_info.size();
5230
5231         while (cell < cells && p < len && row < rows &&
5232                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
5233         {
5234                 if (p >= len)
5235                         break;
5236                 switch (buf[p]) {
5237                 case '\t':
5238                         // we can only set this if we are not too far right
5239                         if (cols < columns) {
5240                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5241                                 Font const font = bv.textMetrics(&inset->text()).
5242                                         displayFont(0, 0);
5243                                 inset->setText(buf.substr(op, p - op), font,
5244                                                buffer().params().trackChanges);
5245                                 ++cols;
5246                                 ++cell;
5247                         }
5248                         break;
5249                 case '\n':
5250                         // we can only set this if we are not too far right
5251                         if (cols < columns) {
5252                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
5253                                 Font const font = bv.textMetrics(&inset->text()).
5254                                         displayFont(0, 0);
5255                                 inset->setText(buf.substr(op, p - op), font,
5256                                                buffer().params().trackChanges);
5257                         }
5258                         cols = ocol;
5259                         ++row;
5260                         if (row < rows)
5261                                 cell = loctab->cellIndex(row, cols);
5262                         break;
5263                 }
5264                 ++p;
5265                 op = p;
5266         }
5267         // check for the last cell if there is no trailing '\n'
5268         if (cell < cells && op < len) {
5269                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5270                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
5271                 inset->setText(buf.substr(op, len - op), font,
5272                         buffer().params().trackChanges);
5273         }
5274         return true;
5275 }
5276
5277
5278 void InsetTabular::addPreview(PreviewLoader & loader) const
5279 {
5280         row_type const rows = tabular.row_info.size();
5281         col_type const columns = tabular.column_info.size();
5282         for (row_type i = 0; i < rows; ++i) {
5283                 for (col_type j = 0; j < columns; ++j)
5284                         tabular.cellInset(i, j)->addPreview(loader);
5285         }
5286 }
5287
5288
5289 bool InsetTabular::completionSupported(Cursor const & cur) const
5290 {
5291         Cursor const & bvCur = cur.bv().cursor();
5292         if (&bvCur.inset() != this)
5293                 return false;
5294         return cur.text()->completionSupported(cur);
5295 }
5296
5297
5298 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
5299 {
5300         return completionSupported(cur);
5301 }
5302
5303
5304 bool InsetTabular::automaticInlineCompletion() const
5305 {
5306         return lyxrc.completion_inline_text;
5307 }
5308
5309
5310 bool InsetTabular::automaticPopupCompletion() const
5311 {
5312         return lyxrc.completion_popup_text;
5313 }
5314
5315
5316 bool InsetTabular::showCompletionCursor() const
5317 {
5318         return lyxrc.completion_cursor_text;
5319 }
5320
5321
5322 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
5323 {
5324         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
5325 }
5326
5327
5328 docstring InsetTabular::completionPrefix(Cursor const & cur) const
5329 {
5330         if (!completionSupported(cur))
5331                 return docstring();
5332         return cur.text()->completionPrefix(cur);
5333 }
5334
5335
5336 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
5337 {
5338         if (!completionSupported(cur))
5339                 return false;
5340
5341         return cur.text()->insertCompletion(cur, s, finished);
5342 }
5343
5344
5345 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
5346                                     Dimension & dim) const
5347 {
5348         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
5349         tm.completionPosAndDim(cur, x, y, dim);
5350 }
5351
5352
5353 void InsetTabular::string2params(string const & in, InsetTabular & inset)
5354 {
5355         istringstream data(in);
5356         Lexer lex;
5357         lex.setStream(data);
5358
5359         if (in.empty())
5360                 return;
5361
5362         string token;
5363         lex >> token;
5364         if (!lex || token != "tabular") {
5365                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
5366                 return;
5367         }
5368
5369         // This is part of the inset proper that is usually swallowed
5370         // by Buffer::readInset
5371         lex >> token;
5372         if (!lex || token != "Tabular") {
5373                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
5374                 return;
5375         }
5376
5377         inset.read(lex);
5378 }
5379
5380
5381 string InsetTabular::params2string(InsetTabular const & inset)
5382 {
5383         ostringstream data;
5384         data << "tabular" << ' ';
5385         inset.write(data);
5386         data << "\\end_inset\n";
5387         return data.str();
5388 }
5389
5390
5391 } // namespace lyx