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