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