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