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