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