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