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