]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
Converted '#warning ...' into FIXME-comments
[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 }
3502
3503
3504 // function sets an object as defined in func_status.h:
3505 // states OK, Unknown, Disabled, On, Off.
3506 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3507         FuncStatus & status) const
3508 {
3509         switch (cmd.action) {
3510         case LFUN_TABULAR_FEATURE: {
3511                 int action = Tabular::LAST_ACTION;
3512                 int i = 0;
3513                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3514                         string const tmp = tabularFeature[i].feature;
3515                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3516                                 action = tabularFeature[i].action;
3517                                 break;
3518                         }
3519                 }
3520                 if (action == Tabular::LAST_ACTION) {
3521                         status.clear();
3522                         status.unknown(true);
3523                         return true;
3524                 }
3525
3526                 string const argument
3527                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3528
3529                 row_type sel_row_start = 0;
3530                 row_type sel_row_end = 0;
3531                 col_type sel_col_start = 0;
3532                 col_type sel_col_end = 0;
3533                 Tabular::ltType dummyltt;
3534                 bool flag = true;
3535
3536                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3537
3538                 switch (action) {
3539                 case Tabular::SET_PWIDTH:
3540                 case Tabular::SET_MPWIDTH:
3541                 case Tabular::SET_SPECIAL_COLUMN:
3542                 case Tabular::SET_SPECIAL_MULTI:
3543                 case Tabular::APPEND_ROW:
3544                 case Tabular::APPEND_COLUMN:
3545                 case Tabular::DELETE_ROW:
3546                 case Tabular::DELETE_COLUMN:
3547                 case Tabular::COPY_ROW:
3548                 case Tabular::COPY_COLUMN:
3549                 case Tabular::SET_ALL_LINES:
3550                 case Tabular::UNSET_ALL_LINES:
3551                 case Tabular::SET_TOP_SPACE:
3552                 case Tabular::SET_BOTTOM_SPACE:
3553                 case Tabular::SET_INTERLINE_SPACE:
3554                         status.clear();
3555                         return true;
3556
3557                 case Tabular::MULTICOLUMN:
3558                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3559                         break;
3560
3561                 case Tabular::M_TOGGLE_LINE_TOP:
3562                         flag = false;
3563                 case Tabular::TOGGLE_LINE_TOP:
3564                         status.setOnOff(tabular.topLine(cur.idx(), flag));
3565                         break;
3566
3567                 case Tabular::M_TOGGLE_LINE_BOTTOM:
3568                         flag = false;
3569                 case Tabular::TOGGLE_LINE_BOTTOM:
3570                         status.setOnOff(tabular.bottomLine(cur.idx(), flag));
3571                         break;
3572
3573                 case Tabular::M_TOGGLE_LINE_LEFT:
3574                         flag = false;
3575                 case Tabular::TOGGLE_LINE_LEFT:
3576                         status.setOnOff(tabular.leftLine(cur.idx(), flag));
3577                         break;
3578
3579                 case Tabular::M_TOGGLE_LINE_RIGHT:
3580                         flag = false;
3581                 case Tabular::TOGGLE_LINE_RIGHT:
3582                         status.setOnOff(tabular.rightLine(cur.idx(), flag));
3583                         break;
3584
3585                 case Tabular::M_ALIGN_LEFT:
3586                         flag = false;
3587                 case Tabular::ALIGN_LEFT:
3588                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3589                         break;
3590
3591                 case Tabular::M_ALIGN_RIGHT:
3592                         flag = false;
3593                 case Tabular::ALIGN_RIGHT:
3594                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3595                         break;
3596
3597                 case Tabular::M_ALIGN_CENTER:
3598                         flag = false;
3599                 case Tabular::ALIGN_CENTER:
3600                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3601                         break;
3602
3603                 case Tabular::ALIGN_BLOCK:
3604                         status.enabled(!tabular.getPWidth(cur.idx()).zero());
3605                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3606                         break;
3607
3608                 case Tabular::M_VALIGN_TOP:
3609                         flag = false;
3610                 case Tabular::VALIGN_TOP:
3611                         status.setOnOff(
3612                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3613                         break;
3614
3615                 case Tabular::M_VALIGN_BOTTOM:
3616                         flag = false;
3617                 case Tabular::VALIGN_BOTTOM:
3618                         status.setOnOff(
3619                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3620                         break;
3621
3622                 case Tabular::M_VALIGN_MIDDLE:
3623                         flag = false;
3624                 case Tabular::VALIGN_MIDDLE:
3625                         status.setOnOff(
3626                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3627                         break;
3628
3629                 case Tabular::SET_LONGTABULAR:
3630                         status.setOnOff(tabular.isLongTabular());
3631                         break;
3632
3633                 case Tabular::UNSET_LONGTABULAR:
3634                         status.setOnOff(!tabular.isLongTabular());
3635                         break;
3636
3637                 case Tabular::TOGGLE_ROTATE_TABULAR:
3638                 case Tabular::SET_ROTATE_TABULAR:
3639                         status.setOnOff(tabular.getRotateTabular());
3640                         break;
3641
3642                 case Tabular::UNSET_ROTATE_TABULAR:
3643                         status.setOnOff(!tabular.getRotateTabular());
3644                         break;
3645
3646                 case Tabular::TOGGLE_ROTATE_CELL:
3647                 case Tabular::SET_ROTATE_CELL:
3648                         status.setOnOff(!oneCellHasRotationState(false,
3649                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3650                         break;
3651
3652                 case Tabular::UNSET_ROTATE_CELL:
3653                         status.setOnOff(!oneCellHasRotationState(true,
3654                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3655                         break;
3656
3657                 case Tabular::SET_USEBOX:
3658                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
3659                         break;
3660
3661                 case Tabular::SET_LTFIRSTHEAD:
3662                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3663                         break;
3664
3665                 case Tabular::UNSET_LTFIRSTHEAD:
3666                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3667                         break;
3668
3669                 case Tabular::SET_LTHEAD:
3670                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3671                         break;
3672
3673                 case Tabular::UNSET_LTHEAD:
3674                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3675                         break;
3676
3677                 case Tabular::SET_LTFOOT:
3678                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3679                         break;
3680
3681                 case Tabular::UNSET_LTFOOT:
3682                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3683                         break;
3684
3685                 case Tabular::SET_LTLASTFOOT:
3686                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3687                         break;
3688
3689                 case Tabular::UNSET_LTLASTFOOT:
3690                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3691                         break;
3692
3693                 case Tabular::SET_LTNEWPAGE:
3694                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
3695                         break;
3696
3697                 case Tabular::SET_BOOKTABS:
3698                         status.setOnOff(tabular.useBookTabs());
3699                         break;
3700
3701                 case Tabular::UNSET_BOOKTABS:
3702                         status.setOnOff(!tabular.useBookTabs());
3703                         break;
3704
3705                 default:
3706                         status.clear();
3707                         status.enabled(false);
3708                         break;
3709                 }
3710                 return true;
3711         }
3712
3713         // These are only enabled inside tabular
3714         case LFUN_CELL_BACKWARD:
3715         case LFUN_CELL_FORWARD:
3716                 status.enabled(true);
3717                 return true;
3718
3719         // disable these with multiple cells selected
3720         case LFUN_INSET_INSERT:
3721         case LFUN_TABULAR_INSERT:
3722         case LFUN_CHARSTYLE_INSERT:
3723         case LFUN_FLOAT_INSERT:
3724         case LFUN_FLOAT_WIDE_INSERT:
3725         case LFUN_FOOTNOTE_INSERT:
3726         case LFUN_MARGINALNOTE_INSERT:
3727         case LFUN_MATH_INSERT:
3728         case LFUN_MATH_MODE:
3729         case LFUN_MATH_MUTATE:
3730         case LFUN_MATH_DISPLAY:
3731         case LFUN_NOTE_INSERT:
3732         case LFUN_OPTIONAL_INSERT:
3733         case LFUN_BOX_INSERT:
3734         case LFUN_BRANCH_INSERT:
3735         case LFUN_WRAP_INSERT:
3736         case LFUN_ERT_INSERT: {
3737                 if (tablemode(cur)) {
3738                         status.enabled(false);
3739                         return true;
3740                 } else
3741                         return cell(cur.idx())->getStatus(cur, cmd, status);
3742         }
3743
3744         // disable in non-fixed-width cells
3745         case LFUN_BREAK_LINE:
3746         case LFUN_BREAK_PARAGRAPH:
3747         case LFUN_BREAK_PARAGRAPH_KEEP_LAYOUT:
3748         case LFUN_BREAK_PARAGRAPH_SKIP: {
3749                 if (tabular.getPWidth(cur.idx()).zero()) {
3750                         status.enabled(false);
3751                         return true;
3752                 } else
3753                         return cell(cur.idx())->getStatus(cur, cmd, status);
3754         }
3755
3756         case LFUN_PASTE:
3757                 if (tabularStackDirty() && theClipboard().isInternal()) {
3758                         status.enabled(true);
3759                         return true;
3760                 } else
3761                         return cell(cur.idx())->getStatus(cur, cmd, status);
3762
3763         case LFUN_INSET_MODIFY:
3764                 if (translate(cmd.getArg(0)) == TABULAR_CODE) {
3765                         status.enabled(true);
3766                         return true;
3767                 }
3768                 // Fall through
3769
3770         default:
3771                 // we try to handle this event in the insets dispatch function.
3772                 return cell(cur.idx())->getStatus(cur, cmd, status);
3773         }
3774 }
3775
3776
3777 int InsetTabular::latex(Buffer const & buf, odocstream & os,
3778                         OutputParams const & runparams) const
3779 {
3780         return tabular.latex(buf, os, runparams);
3781 }
3782
3783
3784 int InsetTabular::plaintext(Buffer const & buf, odocstream & os,
3785                             OutputParams const & runparams) const
3786 {
3787         os << '\n'; // output table on a new line
3788         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
3789         tabular.plaintext(buf, os, runparams, dp, false, 0);
3790         return PLAINTEXT_NEWLINE;
3791 }
3792
3793
3794 int InsetTabular::docbook(Buffer const & buf, odocstream & os,
3795                           OutputParams const & runparams) const
3796 {
3797         int ret = 0;
3798         Inset * master = 0;
3799
3800         // FIXME: Why not pass a proper DocIterator here?
3801 #if 0
3802         // if the table is inside a float it doesn't need the informaltable
3803         // wrapper. Search for it.
3804         for (master = owner(); master; master = master->owner())
3805                 if (master->lyxCode() == Inset::FLOAT_CODE)
3806                         break;
3807 #endif
3808
3809         if (!master) {
3810                 os << "<informaltable>";
3811                 ++ret;
3812         }
3813         ret += tabular.docbook(buf, os, runparams);
3814         if (!master) {
3815                 os << "</informaltable>";
3816                 ++ret;
3817         }
3818         return ret;
3819 }
3820
3821
3822 void InsetTabular::validate(LaTeXFeatures & features) const
3823 {
3824         tabular.validate(features);
3825 }
3826
3827
3828 shared_ptr<InsetText const> InsetTabular::cell(idx_type idx) const
3829 {
3830         return tabular.getCellInset(idx);
3831 }
3832
3833
3834 shared_ptr<InsetText> InsetTabular::cell(idx_type idx)
3835 {
3836         return tabular.getCellInset(idx);
3837 }
3838
3839
3840 void InsetTabular::cursorPos(BufferView const & bv,
3841                 CursorSlice const & sl, bool boundary, int & x, int & y) const
3842 {
3843         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
3844
3845         // y offset     correction
3846         int const row = tabular.row_of_cell(sl.idx());
3847         for (int i = 0; i <= row; ++i) {
3848                 if (i != 0) {
3849                         y += tabular.getAscentOfRow(i);
3850                         y += tabular.getAdditionalHeight(i);
3851                 }
3852                 if (i != row)
3853                         y += tabular.getDescentOfRow(i);
3854         }
3855
3856         // x offset correction
3857         int const col = tabular.column_of_cell(sl.idx());
3858         int idx = tabular.getCellNumber(row, 0);
3859         for (int j = 0; j < col; ++j) {
3860                 if (tabular.isPartOfMultiColumn(row, j))
3861                         continue;
3862                 x += tabular.getWidthOfColumn(idx);
3863                 ++idx;
3864         }
3865         x += tabular.getBeginningOfTextInCell(idx);
3866         x += ADD_TO_TABULAR_WIDTH;
3867         x += scx_;
3868 }
3869
3870
3871 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
3872 {
3873         int xx = 0;
3874         int yy = 0;
3875         Inset const & inset = *tabular.getCellInset(cell);
3876         Point o = bv.coordCache().getInsets().xy(&inset);
3877         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
3878         int const xend = xbeg + tabular.getWidthOfColumn(cell);
3879         row_type const row = tabular.row_of_cell(cell);
3880         int const ybeg = o.y_ - tabular.getAscentOfRow(row) -
3881                          tabular.getAdditionalHeight(row);
3882         int const yend = o.y_ + tabular.getDescentOfRow(row);
3883
3884         if (x < xbeg)
3885                 xx = xbeg - x;
3886         else if (x > xend)
3887                 xx = x - xend;
3888
3889         if (y < ybeg)
3890                 yy = ybeg - y;
3891         else if (y > yend)
3892                 yy = y - yend;
3893
3894         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
3895         //       << " ybeg=" << ybeg << " yend=" << yend
3896         //       << " xx=" << xx << " yy=" << yy
3897         //       << " dist=" << xx + yy << endl;
3898         return xx + yy;
3899 }
3900
3901
3902 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
3903 {
3904         //lyxerr << "InsetTabular::editXY: " << this << endl;
3905         cur.selection() = false;
3906         cur.push(*this);
3907         cur.idx() = getNearestCell(cur.bv(), x, y);
3908         resetPos(cur);
3909         return cell(cur.idx())->text_.editXY(cur, x, y);
3910 }
3911
3912
3913 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
3914 {
3915         cur.idx() = getNearestCell(cur.bv(), x, y);
3916         cell(cur.idx())->text_.setCursorFromCoordinates(cur, x, y);
3917 }
3918
3919
3920 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
3921 {
3922         idx_type idx_min = 0;
3923         int dist_min = std::numeric_limits<int>::max();
3924         for (idx_type i = 0, n = nargs(); i != n; ++i) {
3925                 if (bv.coordCache().getInsets().has(tabular.getCellInset(i).get())) {
3926                         int const d = dist(bv, i, x, y);
3927                         if (d < dist_min) {
3928                                 dist_min = d;
3929                                 idx_min = i;
3930                         }
3931                 }
3932         }
3933         return idx_min;
3934 }
3935
3936
3937 int InsetTabular::getCellXPos(idx_type const cell) const
3938 {
3939         idx_type c = cell;
3940
3941         for (; !tabular.isFirstCellInRow(c); --c)
3942                 ;
3943         int lx = 0;
3944         for (; c < cell; ++c)
3945                 lx += tabular.getWidthOfColumn(c);
3946
3947         return lx;
3948 }
3949
3950
3951 void InsetTabular::resetPos(Cursor & cur) const
3952 {
3953         BufferView & bv = cur.bv();
3954         int const maxwidth = bv.workWidth();
3955
3956         if (&cur.inset() != this) {
3957                 scx_ = 0;
3958         } else {
3959                 int const X1 = 0;
3960                 int const X2 = maxwidth;
3961                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
3962                 int const x1 = xo(cur.bv()) + getCellXPos(cur.idx()) + offset;
3963                 int const x2 = x1 + tabular.getWidthOfColumn(cur.idx());
3964
3965                 if (x1 < X1)
3966                         scx_ = X1 + 20 - x1;
3967                 else if (x2 > X2)
3968                         scx_ = X2 - 20 - x2;
3969                 else
3970                         scx_ = 0;
3971         }
3972
3973         cur.updateFlags(Update::Force | Update::FitCursor);
3974 }
3975
3976
3977 void InsetTabular::moveNextCell(Cursor & cur)
3978 {
3979         if (isRightToLeft(cur)) {
3980                 if (tabular.isFirstCellInRow(cur.idx())) {
3981                         row_type const row = tabular.row_of_cell(cur.idx());
3982                         if (row == tabular.rows() - 1)
3983                                 return;
3984                         cur.idx() = tabular.getCellBelow(tabular.getLastCellInRow(row));
3985                 } else {
3986                         if (cur.idx() == 0)
3987                                 return;
3988                         --cur.idx();
3989                 }
3990         } else {
3991                 if (tabular.isLastCell(cur.idx()))
3992                         return;
3993                 ++cur.idx();
3994         }
3995         cur.pit() = 0;
3996         cur.pos() = 0;
3997         resetPos(cur);
3998 }
3999
4000
4001 void InsetTabular::movePrevCell(Cursor & cur)
4002 {
4003         if (isRightToLeft(cur)) {
4004                 if (tabular.isLastCellInRow(cur.idx())) {
4005                         row_type const row = tabular.row_of_cell(cur.idx());
4006                         if (row == 0)
4007                                 return;
4008                         cur.idx() = tabular.getFirstCellInRow(row);
4009                         cur.idx() = tabular.getCellAbove(cur.idx());
4010                 } else {
4011                         if (tabular.isLastCell(cur.idx()))
4012                                 return;
4013                         ++cur.idx();
4014                 }
4015         } else {
4016                 if (cur.idx() == 0) // first cell
4017                         return;
4018                 --cur.idx();
4019         }
4020         cur.pit() = cur.lastpit();
4021         cur.pos() = cur.lastpos();
4022
4023         // FIXME: this accesses the position cache before it is initialized
4024         //resetPos(cur);
4025 }
4026
4027
4028 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4029 {
4030         Tabular::Feature action = Tabular::LAST_ACTION;
4031
4032         int i = 0;
4033         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4034                 string const tmp = tabularFeature[i].feature;
4035
4036                 if (tmp == what.substr(0, tmp.length())) {
4037                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4038                         //tabularFeatures[i].feature.length()))
4039                         action = tabularFeature[i].action;
4040                         break;
4041                 }
4042         }
4043         if (action == Tabular::LAST_ACTION)
4044                 return false;
4045
4046         string const val =
4047                 ltrim(what.substr(tabularFeature[i].feature.length()));
4048         tabularFeatures(cur, action, val);
4049         return true;
4050 }
4051
4052
4053 static void checkLongtableSpecial(Tabular::ltType & ltt,
4054                           string const & special, bool & flag)
4055 {
4056         if (special == "dl_above") {
4057                 ltt.topDL = flag;
4058                 ltt.set = false;
4059         } else if (special == "dl_below") {
4060                 ltt.bottomDL = flag;
4061                 ltt.set = false;
4062         } else if (special == "empty") {
4063                 ltt.empty = flag;
4064                 ltt.set = false;
4065         } else if (flag) {
4066                 ltt.empty = false;
4067                 ltt.set = true;
4068         }
4069 }
4070
4071 bool InsetTabular::oneCellHasRotationState(bool rotated,
4072                 row_type row_start, row_type row_end,
4073                 col_type col_start, col_type col_end) const {
4074
4075         for (row_type i = row_start; i <= row_end; ++i) {
4076                 for (col_type j = col_start; j <= col_end; ++j) {
4077                         if (tabular.getRotateCell(tabular.getCellNumber(i, j))
4078                                 == rotated) {
4079                                 return true;
4080                         }
4081                 }
4082         }
4083         return false;
4084 }
4085
4086 void InsetTabular::tabularFeatures(Cursor & cur,
4087         Tabular::Feature feature, string const & value)
4088 {
4089         BufferView & bv = cur.bv();
4090         col_type sel_col_start;
4091         col_type sel_col_end;
4092         row_type sel_row_start;
4093         row_type sel_row_end;
4094         bool setLines = false;
4095         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4096         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4097
4098         switch (feature) {
4099
4100         case Tabular::M_ALIGN_LEFT:
4101         case Tabular::ALIGN_LEFT:
4102                 setAlign = LYX_ALIGN_LEFT;
4103                 break;
4104
4105         case Tabular::M_ALIGN_RIGHT:
4106         case Tabular::ALIGN_RIGHT:
4107                 setAlign = LYX_ALIGN_RIGHT;
4108                 break;
4109
4110         case Tabular::M_ALIGN_CENTER:
4111         case Tabular::ALIGN_CENTER:
4112                 setAlign = LYX_ALIGN_CENTER;
4113                 break;
4114
4115         case Tabular::ALIGN_BLOCK:
4116                 setAlign = LYX_ALIGN_BLOCK;
4117                 break;
4118
4119         case Tabular::M_VALIGN_TOP:
4120         case Tabular::VALIGN_TOP:
4121                 setVAlign = Tabular::LYX_VALIGN_TOP;
4122                 break;
4123
4124         case Tabular::M_VALIGN_BOTTOM:
4125         case Tabular::VALIGN_BOTTOM:
4126                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4127                 break;
4128
4129         case Tabular::M_VALIGN_MIDDLE:
4130         case Tabular::VALIGN_MIDDLE:
4131                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4132                 break;
4133
4134         default:
4135                 break;
4136         }
4137
4138         recordUndoInset(cur, Undo::ATOMIC);
4139
4140         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4141         row_type const row = tabular.row_of_cell(cur.idx());
4142         col_type const column = tabular.column_of_cell(cur.idx());
4143         bool flag = true;
4144         Tabular::ltType ltt;
4145
4146         switch (feature) {
4147
4148         case Tabular::SET_PWIDTH: {
4149                 Length const len(value);
4150                 tabular.setColumnPWidth(cur, cur.idx(), len);
4151                 if (len.zero()
4152                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4153                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4154                 break;
4155         }
4156
4157         case Tabular::SET_MPWIDTH:
4158                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4159                 break;
4160
4161         case Tabular::SET_SPECIAL_COLUMN:
4162         case Tabular::SET_SPECIAL_MULTI:
4163                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4164                 break;
4165
4166         case Tabular::APPEND_ROW:
4167                 // append the row into the tabular
4168                 tabular.appendRow(bv.buffer()->params(), cur.idx());
4169                 break;
4170
4171         case Tabular::APPEND_COLUMN:
4172                 // append the column into the tabular
4173                 tabular.appendColumn(bv.buffer()->params(), cur.idx());
4174                 cur.idx() = tabular.getCellNumber(row, column);
4175                 break;
4176
4177         case Tabular::DELETE_ROW:
4178                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4179                         tabular.deleteRow(sel_row_start);
4180                 if (sel_row_start >= tabular.rows())
4181                         --sel_row_start;
4182                 cur.idx() = tabular.getCellNumber(sel_row_start, column);
4183                 cur.pit() = 0;
4184                 cur.pos() = 0;
4185                 cur.selection() = false;
4186                 break;
4187
4188         case Tabular::DELETE_COLUMN:
4189                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4190                         tabular.deleteColumn(sel_col_start);
4191                 if (sel_col_start >= tabular.columns())
4192                         --sel_col_start;
4193                 cur.idx() = tabular.getCellNumber(row, sel_col_start);
4194                 cur.pit() = 0;
4195                 cur.pos() = 0;
4196                 cur.selection() = false;
4197                 break;
4198
4199         case Tabular::COPY_ROW:
4200                 tabular.copyRow(bv.buffer()->params(), row);
4201                 break;
4202
4203         case Tabular::COPY_COLUMN:
4204                 tabular.copyColumn(bv.buffer()->params(), column);
4205                 cur.idx() = tabular.getCellNumber(row, column);
4206                 break;
4207
4208         case Tabular::M_TOGGLE_LINE_TOP:
4209                 flag = false;
4210         case Tabular::TOGGLE_LINE_TOP: {
4211                 bool lineSet = !tabular.topLine(cur.idx(), flag);
4212                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4213                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4214                                 tabular.setTopLine(
4215                                         tabular.getCellNumber(i, j),
4216                                         lineSet, flag);
4217                 break;
4218         }
4219
4220         case Tabular::M_TOGGLE_LINE_BOTTOM:
4221                 flag = false;
4222         case Tabular::TOGGLE_LINE_BOTTOM: {
4223                 bool lineSet = !tabular.bottomLine(cur.idx(), flag);
4224                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4225                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4226                                 tabular.setBottomLine(
4227                                         tabular.getCellNumber(i, j),
4228                                         lineSet,
4229                                         flag);
4230                 break;
4231         }
4232
4233         case Tabular::M_TOGGLE_LINE_LEFT:
4234                 flag = false;
4235         case Tabular::TOGGLE_LINE_LEFT: {
4236                 bool lineSet = !tabular.leftLine(cur.idx(), flag);
4237                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4238                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4239                                 tabular.setLeftLine(
4240                                         tabular.getCellNumber(i,j),
4241                                         lineSet,
4242                                         flag);
4243                 break;
4244         }
4245
4246         case Tabular::M_TOGGLE_LINE_RIGHT:
4247                 flag = false;
4248         case Tabular::TOGGLE_LINE_RIGHT: {
4249                 bool lineSet = !tabular.rightLine(cur.idx(), flag);
4250                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4251                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4252                                 tabular.setRightLine(
4253                                         tabular.getCellNumber(i,j),
4254                                         lineSet,
4255                                         flag);
4256                 break;
4257         }
4258
4259         case Tabular::M_ALIGN_LEFT:
4260         case Tabular::M_ALIGN_RIGHT:
4261         case Tabular::M_ALIGN_CENTER:
4262                 flag = false;
4263         case Tabular::ALIGN_LEFT:
4264         case Tabular::ALIGN_RIGHT:
4265         case Tabular::ALIGN_CENTER:
4266         case Tabular::ALIGN_BLOCK:
4267                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4268                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4269                                 tabular.setAlignment(
4270                                         tabular.getCellNumber(i, j),
4271                                         setAlign,
4272                                         flag);
4273                 break;
4274
4275         case Tabular::M_VALIGN_TOP:
4276         case Tabular::M_VALIGN_BOTTOM:
4277         case Tabular::M_VALIGN_MIDDLE:
4278                 flag = false;
4279         case Tabular::VALIGN_TOP:
4280         case Tabular::VALIGN_BOTTOM:
4281         case Tabular::VALIGN_MIDDLE:
4282                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4283                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4284                                 tabular.setVAlignment(
4285                                         tabular.getCellNumber(i, j),
4286                                         setVAlign, flag);
4287                 break;
4288
4289         case Tabular::MULTICOLUMN: {
4290                 if (sel_row_start != sel_row_end) {
4291                         // FIXME: Need I say it ? This is horrible.
4292                         // FIXME UNICODE
4293                         Alert::error(_("Error setting multicolumn"),
4294                                      _("You cannot set multicolumn vertically."));
4295                         return;
4296                 }
4297                 if (!cur.selection()) {
4298                         // just multicol for one single cell
4299                         // check whether we are completely in a multicol
4300                         if (tabular.isMultiColumn(cur.idx()))
4301                                 tabular.unsetMultiColumn(cur.idx());
4302                         else
4303                                 tabular.setMultiColumn(bv.buffer(), cur.idx(), 1);
4304                         break;
4305                 }
4306                 // we have a selection so this means we just add all this
4307                 // cells to form a multicolumn cell
4308                 idx_type const s_start = cur.selBegin().idx();
4309                 idx_type const s_end = cur.selEnd().idx();
4310                 tabular.setMultiColumn(bv.buffer(), s_start, s_end - s_start + 1);
4311                 cur.idx() = s_start;
4312                 cur.pit() = 0;
4313                 cur.pos() = 0;
4314                 cur.selection() = false;
4315                 break;
4316         }
4317
4318         case Tabular::SET_ALL_LINES:
4319                 setLines = true;
4320         case Tabular::UNSET_ALL_LINES:
4321                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4322                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4323                                 tabular.setAllLines(
4324                                         tabular.getCellNumber(i,j), setLines);
4325                 break;
4326
4327         case Tabular::SET_LONGTABULAR:
4328                 tabular.setLongTabular(true);
4329                 break;
4330
4331         case Tabular::UNSET_LONGTABULAR:
4332                 tabular.setLongTabular(false);
4333                 break;
4334
4335         case Tabular::SET_ROTATE_TABULAR:
4336                 tabular.setRotateTabular(true);
4337                 break;
4338
4339         case Tabular::UNSET_ROTATE_TABULAR:
4340                 tabular.setRotateTabular(false);
4341                 break;
4342
4343         case Tabular::TOGGLE_ROTATE_TABULAR:
4344                 tabular.setRotateTabular(!tabular.getRotateTabular());
4345                 break;
4346
4347         case Tabular::SET_ROTATE_CELL:
4348                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4349                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4350                                 tabular.setRotateCell(
4351                                         tabular.getCellNumber(i, j), true);
4352                 break;
4353
4354         case Tabular::UNSET_ROTATE_CELL:
4355                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4356                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4357                                 tabular.setRotateCell(
4358                                         tabular.getCellNumber(i, j), false);
4359                 break;
4360
4361         case Tabular::TOGGLE_ROTATE_CELL:
4362                 {
4363                 bool oneNotRotated = oneCellHasRotationState(false,
4364                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4365
4366                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4367                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4368                                 tabular.setRotateCell(tabular.getCellNumber(i, j),
4369                                                                           oneNotRotated);
4370                 }
4371                 break;
4372
4373         case Tabular::SET_USEBOX: {
4374                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4375                 if (val == tabular.getUsebox(cur.idx()))
4376                         val = Tabular::BOX_NONE;
4377                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4378                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4379                                 tabular.setUsebox(tabular.getCellNumber(i, j), val);
4380                 break;
4381         }
4382
4383         case Tabular::UNSET_LTFIRSTHEAD:
4384                 flag = false;
4385         case Tabular::SET_LTFIRSTHEAD:
4386                 tabular.getRowOfLTFirstHead(row, ltt);
4387                 checkLongtableSpecial(ltt, value, flag);
4388                 tabular.setLTHead(row, flag, ltt, true);
4389                 break;
4390
4391         case Tabular::UNSET_LTHEAD:
4392                 flag = false;
4393         case Tabular::SET_LTHEAD:
4394                 tabular.getRowOfLTHead(row, ltt);
4395                 checkLongtableSpecial(ltt, value, flag);
4396                 tabular.setLTHead(row, flag, ltt, false);
4397                 break;
4398
4399         case Tabular::UNSET_LTFOOT:
4400                 flag = false;
4401         case Tabular::SET_LTFOOT:
4402                 tabular.getRowOfLTFoot(row, ltt);
4403                 checkLongtableSpecial(ltt, value, flag);
4404                 tabular.setLTFoot(row, flag, ltt, false);
4405                 break;
4406
4407         case Tabular::UNSET_LTLASTFOOT:
4408                 flag = false;
4409         case Tabular::SET_LTLASTFOOT:
4410                 tabular.getRowOfLTLastFoot(row, ltt);
4411                 checkLongtableSpecial(ltt, value, flag);
4412                 tabular.setLTFoot(row, flag, ltt, true);
4413                 break;
4414
4415         case Tabular::SET_LTNEWPAGE:
4416                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4417                 break;
4418
4419         case Tabular::SET_BOOKTABS:
4420                 tabular.setBookTabs(true);
4421                 break;
4422
4423         case Tabular::UNSET_BOOKTABS:
4424                 tabular.setBookTabs(false);
4425                 break;
4426
4427         case Tabular::SET_TOP_SPACE: {
4428                 Length len;
4429                 if (value == "default")
4430                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4431                                 tabular.row_info[i].top_space_default = true;
4432                 else if (isValidLength(value, &len))
4433                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4434                                 tabular.row_info[i].top_space_default = false;
4435                                 tabular.row_info[i].top_space = len;
4436                         }
4437                 else
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                 break;
4443         }
4444
4445         case Tabular::SET_BOTTOM_SPACE: {
4446                 Length len;
4447                 if (value == "default")
4448                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4449                                 tabular.row_info[i].bottom_space_default = true;
4450                 else if (isValidLength(value, &len))
4451                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4452                                 tabular.row_info[i].bottom_space_default = false;
4453                                 tabular.row_info[i].bottom_space = len;
4454                         }
4455                 else
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                 break;
4461         }
4462
4463         case Tabular::SET_INTERLINE_SPACE: {
4464                 Length len;
4465                 if (value == "default")
4466                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4467                                 tabular.row_info[i].interline_space_default = true;
4468                 else if (isValidLength(value, &len))
4469                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4470                                 tabular.row_info[i].interline_space_default = false;
4471                                 tabular.row_info[i].interline_space = len;
4472                         }
4473                 else
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                 break;
4479         }
4480
4481         // dummy stuff just to avoid warnings
4482         case Tabular::LAST_ACTION:
4483                 break;
4484         }
4485 }
4486
4487
4488 bool InsetTabular::showInsetDialog(BufferView * bv) const
4489 {
4490         InsetTabularMailer(*this).showDialog(bv);
4491         return true;
4492 }
4493
4494
4495 void InsetTabular::openLayoutDialog(BufferView * bv) const
4496 {
4497         InsetTabularMailer(*this).showDialog(bv);
4498 }
4499
4500
4501 bool InsetTabular::copySelection(Cursor & cur)
4502 {
4503         if (!cur.selection())
4504                 return false;
4505
4506         row_type rs, re;
4507         col_type cs, ce;
4508         getSelection(cur, rs, re, cs, ce);
4509
4510         paste_tabular.reset(new Tabular(tabular));
4511
4512         for (row_type i = 0; i < rs; ++i)
4513                 paste_tabular->deleteRow(0);
4514
4515         row_type const rows = re - rs + 1;
4516         while (paste_tabular->rows() > rows)
4517                 paste_tabular->deleteRow(rows);
4518
4519         paste_tabular->setTopLine(0, true, true);
4520         paste_tabular->setBottomLine(paste_tabular->getFirstCellInRow(rows - 1),
4521                                      true, true);
4522
4523         for (col_type i = 0; i < cs; ++i)
4524                 paste_tabular->deleteColumn(0);
4525
4526         col_type const columns = ce - cs + 1;
4527         while (paste_tabular->columns() > columns)
4528                 paste_tabular->deleteColumn(columns);
4529
4530         paste_tabular->setLeftLine(0, true, true);
4531         paste_tabular->setRightLine(paste_tabular->getLastCellInRow(0),
4532                                     true, true);
4533
4534         odocstringstream os;
4535         OutputParams const runparams(0);
4536         paste_tabular->plaintext(cur.buffer(), os, runparams, 0, true, '\t');
4537         // Needed for the "Edit->Paste recent" menu and the system clipboard.
4538         cap::copySelection(cur, os.str());
4539
4540         // mark tabular stack dirty
4541         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
4542         // when we (hopefully) have a one-for-all paste mechanism.
4543         // This must be called after cap::copySelection.
4544         dirtyTabularStack(true);
4545
4546         return true;
4547 }
4548
4549
4550 bool InsetTabular::pasteClipboard(Cursor & cur)
4551 {
4552         if (!paste_tabular)
4553                 return false;
4554         col_type const actcol = tabular.column_of_cell(cur.idx());
4555         row_type const actrow = tabular.row_of_cell(cur.idx());
4556         for (row_type r1 = 0, r2 = actrow;
4557              r1 < paste_tabular->rows() && r2 < tabular.rows();
4558              ++r1, ++r2) {
4559                 for (col_type c1 = 0, c2 = actcol;
4560                     c1 < paste_tabular->columns() && c2 < tabular.columns();
4561                     ++c1, ++c2) {
4562                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
4563                             tabular.isPartOfMultiColumn(r2, c2))
4564                                 continue;
4565                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
4566                                 --c2;
4567                                 continue;
4568                         }
4569                         if (tabular.isPartOfMultiColumn(r2, c2)) {
4570                                 --c1;
4571                                 continue;
4572                         }
4573                         shared_ptr<InsetText> inset(
4574                                 new InsetText(*paste_tabular->getCellInset(r1, c1)));
4575                         tabular.setCellInset(r2, c2, inset);
4576                         // FIXME: change tracking (MG)
4577                         inset->setChange(Change(cur.buffer().params().trackChanges ?
4578                                                 Change::INSERTED : Change::UNCHANGED));
4579                         cur.pos() = 0;
4580                 }
4581         }
4582         return true;
4583 }
4584
4585
4586 void InsetTabular::cutSelection(Cursor & cur)
4587 {
4588         if (!cur.selection())
4589                 return;
4590
4591         row_type rs, re;
4592         col_type cs, ce;
4593         getSelection(cur, rs, re, cs, ce);
4594         for (row_type i = rs; i <= re; ++i) {
4595                 for (col_type j = cs; j <= ce; ++j) {
4596                         shared_ptr<InsetText> t
4597                                 = cell(tabular.getCellNumber(i, j));
4598                         if (cur.buffer().params().trackChanges)
4599                                 // FIXME: Change tracking (MG)
4600                                 t->setChange(Change(Change::DELETED));
4601                         else
4602                                 t->clear();
4603                 }
4604         }
4605
4606         // cursor position might be invalid now
4607         if (cur.pit() > cur.lastpit())
4608                 cur.pit() = cur.lastpit();
4609         if (cur.pos() > cur.lastpos())
4610                 cur.pos() = cur.lastpos();
4611         cur.clearSelection();
4612 }
4613
4614
4615 bool InsetTabular::isRightToLeft(Cursor & cur) const
4616 {
4617         BOOST_ASSERT(cur.depth() > 1);
4618         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
4619         pos_type const parentpos = cur[cur.depth() - 2].pos();
4620         return parentpar.getFontSettings(cur.bv().buffer()->params(),
4621                                          parentpos).language()->rightToLeft();
4622 }
4623
4624
4625 void InsetTabular::getSelection(Cursor & cur,
4626         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
4627 {
4628         CursorSlice const & beg = cur.selBegin();
4629         CursorSlice const & end = cur.selEnd();
4630         cs = tabular.column_of_cell(beg.idx());
4631         ce = tabular.column_of_cell(end.idx());
4632         if (cs > ce) {
4633                 ce = cs;
4634                 cs = tabular.column_of_cell(end.idx());
4635         } else {
4636                 ce = tabular.right_column_of_cell(end.idx());
4637         }
4638
4639         rs = tabular.row_of_cell(beg.idx());
4640         re = tabular.row_of_cell(end.idx());
4641         if (rs > re)
4642                 swap(rs, re);
4643 }
4644
4645
4646 Text * InsetTabular::getText(int idx) const
4647 {
4648         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
4649 }
4650
4651
4652 void InsetTabular::setChange(Change const & change)
4653 {
4654         for (idx_type idx = 0; idx < nargs(); ++idx)
4655                 cell(idx)->setChange(change);
4656 }
4657
4658
4659 void InsetTabular::acceptChanges(BufferParams const & bparams)
4660 {
4661         for (idx_type idx = 0; idx < nargs(); ++idx)
4662                 cell(idx)->acceptChanges(bparams);
4663 }
4664
4665
4666 void InsetTabular::rejectChanges(BufferParams const & bparams)
4667 {
4668         for (idx_type idx = 0; idx < nargs(); ++idx)
4669                 cell(idx)->rejectChanges(bparams);
4670 }
4671
4672
4673 bool InsetTabular::forceDefaultParagraphs(idx_type cell) const
4674 {
4675         return tabular.getPWidth(cell).zero();
4676 }
4677
4678
4679 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
4680                                      bool usePaste)
4681 {
4682         if (buf.length() <= 0)
4683                 return true;
4684
4685         Buffer const & buffer = *bv.buffer();
4686
4687         col_type cols = 1;
4688         row_type rows = 1;
4689         col_type maxCols = 1;
4690         docstring::size_type const len = buf.length();
4691         docstring::size_type p = 0;
4692
4693         while (p < len &&
4694                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
4695                 switch (buf[p]) {
4696                 case '\t':
4697                         ++cols;
4698                         break;
4699                 case '\n':
4700                         if (p + 1 < len)
4701                                 ++rows;
4702                         maxCols = max(cols, maxCols);
4703                         cols = 1;
4704                         break;
4705                 }
4706                 ++p;
4707         }
4708         maxCols = max(cols, maxCols);
4709         Tabular * loctab;
4710         idx_type cell = 0;
4711         col_type ocol = 0;
4712         row_type row = 0;
4713         if (usePaste) {
4714                 paste_tabular.reset(
4715                         new Tabular(buffer.params(), rows, maxCols));
4716                 loctab = paste_tabular.get();
4717                 cols = 0;
4718                 dirtyTabularStack(true);
4719         } else {
4720                 loctab = &tabular;
4721                 cell = bv.cursor().idx();
4722                 ocol = tabular.column_of_cell(cell);
4723                 row = tabular.row_of_cell(cell);
4724         }
4725
4726         docstring::size_type op = 0;
4727         idx_type const cells = loctab->getNumberOfCells();
4728         p = 0;
4729         cols = ocol;
4730         rows = loctab->rows();
4731         col_type const columns = loctab->columns();
4732
4733         while (cell < cells && p < len && row < rows &&
4734                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
4735         {
4736                 if (p >= len)
4737                         break;
4738                 switch (buf[p]) {
4739                 case '\t':
4740                         // we can only set this if we are not too far right
4741                         if (cols < columns) {
4742                                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
4743                                 Paragraph & par = inset->text_.getPar(0);
4744                                 Font const font = inset->text_.getFont(buffer, par, 0);
4745                                 inset->setText(buf.substr(op, p - op), font,
4746                                                buffer.params().trackChanges);
4747                                 ++cols;
4748                                 ++cell;
4749                         }
4750                         break;
4751                 case '\n':
4752                         // we can only set this if we are not too far right
4753                         if (cols < columns) {
4754                                 shared_ptr<InsetText> inset = tabular.getCellInset(cell);
4755                                 Paragraph & par = inset->text_.getPar(0);
4756                                 Font const font = inset->text_.getFont(buffer, par, 0);
4757                                 inset->setText(buf.substr(op, p - op), font,
4758                                                buffer.params().trackChanges);
4759                         }
4760                         cols = ocol;
4761                         ++row;
4762                         if (row < rows)
4763                                 cell = loctab->getCellNumber(row, cols);
4764                         break;
4765                 }
4766                 ++p;
4767                 op = p;
4768         }
4769         // check for the last cell if there is no trailing '\n'
4770         if (cell < cells && op < len) {
4771                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
4772                 Paragraph & par = inset->text_.getPar(0);
4773                 Font const font = inset->text_.getFont(buffer, par, 0);
4774                 inset->setText(buf.substr(op, len - op), font,
4775                         buffer.params().trackChanges);
4776         }
4777         return true;
4778 }
4779
4780
4781 void InsetTabular::addPreview(PreviewLoader & loader) const
4782 {
4783         row_type const rows = tabular.rows();
4784         col_type const columns = tabular.columns();
4785         for (row_type i = 0; i < rows; ++i) {
4786                 for (col_type j = 0; j < columns; ++j)
4787                         tabular.getCellInset(i, j)->addPreview(loader);
4788         }
4789 }
4790
4791
4792 bool InsetTabular::tablemode(Cursor & cur) const
4793 {
4794         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
4795 }
4796
4797
4798
4799
4800
4801 string const InsetTabularMailer::name_("tabular");
4802
4803 InsetTabularMailer::InsetTabularMailer(InsetTabular const & inset)
4804         : inset_(const_cast<InsetTabular &>(inset))
4805 {}
4806
4807
4808 string const InsetTabularMailer::inset2string(Buffer const &) const
4809 {
4810         return params2string(inset_);
4811 }
4812
4813
4814 void InsetTabularMailer::string2params(string const & in, InsetTabular & inset)
4815 {
4816         istringstream data(in);
4817         Lexer lex(0,0);
4818         lex.setStream(data);
4819
4820         if (in.empty())
4821                 return;
4822
4823         string token;
4824         lex >> token;
4825         if (!lex || token != name_)
4826                 return print_mailer_error("InsetTabularMailer", in, 1,
4827                                           name_);
4828
4829         // This is part of the inset proper that is usually swallowed
4830         // by Buffer::readInset
4831         lex >> token;
4832         if (!lex || token != "Tabular")
4833                 return print_mailer_error("InsetTabularMailer", in, 2,
4834                                           "Tabular");
4835
4836         Buffer const & buffer = inset.buffer();
4837         inset.read(buffer, lex);
4838 }
4839
4840
4841 string const InsetTabularMailer::params2string(InsetTabular const & inset)
4842 {
4843         ostringstream data;
4844         data << name_ << ' ';
4845         inset.write(inset.buffer(), data);
4846         data << "\\end_inset\n";
4847         return data.str();
4848 }
4849
4850
4851 } // namespace lyx