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