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