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