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