]> git.lyx.org Git - features.git/blob - src/insets/InsetTabular.cpp
reduce line noise
[features.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_funcs.h"
24 #include "Buffer.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "CoordCache.h"
28 #include "Counters.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "debug.h"
32 #include "DispatchResult.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "gettext.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "Lexer.h"
39 #include "LyXFunc.h"
40 #include "MetricsInfo.h"
41 #include "OutputParams.h"
42 #include "paragraph_funcs.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
48
49 #include "support/convert.h"
50 #include "support/docstream.h"
51 #include "support/lstrings.h"
52
53 #include "frontends/alert.h"
54 #include "frontends/Clipboard.h"
55 #include "frontends/Painter.h"
56 #include "frontends/Selection.h"
57
58 #include <boost/scoped_ptr.hpp>
59
60 #include <sstream>
61 #include <iostream>
62 #include <limits>
63
64 using std::abs;
65 using std::endl;
66 using std::getline;
67 using std::istream;
68 using std::istringstream;
69 using std::max;
70 using std::ostream;
71 using std::ostringstream;
72 using std::string;
73 using std::swap;
74 using std::vector;
75
76 #ifndef CXX_GLOBAL_CSTD
77 using std::strlen;
78 #endif
79
80 using boost::shared_ptr;
81 using boost::dynamic_pointer_cast;
82
83 namespace lyx {
84
85 using support::prefixIs;
86 using support::ltrim;
87 using support::rtrim;
88 using support::suffixIs;
89
90 using cap::dirtyTabularStack;
91 using cap::tabularStackDirty;
92
93 using graphics::PreviewLoader;
94
95 using frontend::Painter;
96 using frontend::Clipboard;
97
98 namespace Alert = frontend::Alert;
99
100
101 namespace {
102
103 int const ADD_TO_HEIGHT = 2;
104 int const ADD_TO_TABULAR_WIDTH = 2;
105 int const default_line_space = 10;
106 int const WIDTH_OF_LINE = 5;
107
108
109 ///
110 boost::scoped_ptr<Tabular> paste_tabular;
111
112
113 struct TabularFeature {
114         Tabular::Feature action;
115         string feature;
116 };
117
118
119 TabularFeature tabularFeature[] =
120 {
121         { Tabular::APPEND_ROW, "append-row" },
122         { Tabular::APPEND_COLUMN, "append-column" },
123         { Tabular::DELETE_ROW, "delete-row" },
124         { Tabular::DELETE_COLUMN, "delete-column" },
125         { Tabular::COPY_ROW, "copy-row" },
126         { Tabular::COPY_COLUMN, "copy-column" },
127         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top" },
128         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
129         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
130         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
131         { Tabular::ALIGN_LEFT, "align-left" },
132         { Tabular::ALIGN_RIGHT, "align-right" },
133         { Tabular::ALIGN_CENTER, "align-center" },
134         { Tabular::ALIGN_BLOCK, "align-block" },
135         { Tabular::VALIGN_TOP, "valign-top" },
136         { Tabular::VALIGN_BOTTOM, "valign-bottom" },
137         { Tabular::VALIGN_MIDDLE, "valign-middle" },
138         { Tabular::M_TOGGLE_LINE_TOP, "m-toggle-line-top" },
139         { Tabular::M_TOGGLE_LINE_BOTTOM, "m-toggle-line-bottom" },
140         { Tabular::M_TOGGLE_LINE_LEFT, "m-toggle-line-left" },
141         { Tabular::M_TOGGLE_LINE_RIGHT, "m-toggle-line-right" },
142         { Tabular::M_ALIGN_LEFT, "m-align-left" },
143         { Tabular::M_ALIGN_RIGHT, "m-align-right" },
144         { Tabular::M_ALIGN_CENTER, "m-align-center" },
145         { Tabular::M_VALIGN_TOP, "m-valign-top" },
146         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
147         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle" },
148         { Tabular::MULTICOLUMN, "multicolumn" },
149         { Tabular::SET_ALL_LINES, "set-all-lines" },
150         { Tabular::UNSET_ALL_LINES, "unset-all-lines" },
151         { Tabular::SET_LONGTABULAR, "set-longtabular" },
152         { Tabular::UNSET_LONGTABULAR, "unset-longtabular" },
153         { Tabular::SET_PWIDTH, "set-pwidth" },
154         { Tabular::SET_MPWIDTH, "set-mpwidth" },
155         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
156         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
157         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular" },
158         { Tabular::SET_ROTATE_CELL, "set-rotate-cell" },
159         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
160         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell" },
161         { Tabular::SET_USEBOX, "set-usebox" },
162         { Tabular::SET_LTHEAD, "set-lthead" },
163         { Tabular::UNSET_LTHEAD, "unset-lthead" },
164         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
165         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead" },
166         { Tabular::SET_LTFOOT, "set-ltfoot" },
167         { Tabular::UNSET_LTFOOT, "unset-ltfoot" },
168         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot" },
169         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot" },
170         { Tabular::SET_LTNEWPAGE, "set-ltnewpage" },
171         { Tabular::SET_SPECIAL_COLUMN, "set-special-column" },
172         { Tabular::SET_SPECIAL_MULTI, "set-special-multi" },
173         { Tabular::SET_BOOKTABS, "set-booktabs" },
174         { Tabular::UNSET_BOOKTABS, "unset-booktabs" },
175         { Tabular::SET_TOP_SPACE, "set-top-space" },
176         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space" },
177         { Tabular::SET_INTERLINE_SPACE, "set-interline-space" },
178         { Tabular::LAST_ACTION, "" }
179 };
180
181
182 class FeatureEqual : public std::unary_function<TabularFeature, bool> {
183 public:
184         FeatureEqual(Tabular::Feature feature)
185                 : feature_(feature) {}
186         bool operator()(TabularFeature const & tf) const {
187                 return tf.action == feature_;
188         }
189 private:
190         Tabular::Feature feature_;
191 };
192
193
194 template <class T>
195 string const write_attribute(string const & name, T const & t)
196 {
197         string const s = tostr(t);
198         return s.empty() ? s : " " + name + "=\"" + s + "\"";
199 }
200
201 template <>
202 string const write_attribute(string const & name, string const & t)
203 {
204         return t.empty() ? t : " " + name + "=\"" + t + "\"";
205 }
206
207
208 template <>
209 string const write_attribute(string const & name, docstring const & t)
210 {
211         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
212 }
213
214
215 template <>
216 string const write_attribute(string const & name, bool const & b)
217 {
218         // we write only true attribute values so we remove a bit of the
219         // file format bloat for tabulars.
220         return b ? write_attribute(name, convert<string>(b)) : string();
221 }
222
223
224 template <>
225 string const write_attribute(string const & name, int const & i)
226 {
227         // we write only true attribute values so we remove a bit of the
228         // file format bloat for tabulars.
229         return i ? write_attribute(name, convert<string>(i)) : string();
230 }
231
232
233 template <>
234 string const write_attribute(string const & name, Tabular::idx_type const & i)
235 {
236         // we write only true attribute values so we remove a bit of the
237         // file format bloat for tabulars.
238         return i ? write_attribute(name, convert<string>(i)) : string();
239 }
240
241
242 template <>
243 string const write_attribute(string const & name, Length const & value)
244 {
245         // we write only the value if we really have one same reson as above.
246         return value.zero() ? string() : write_attribute(name, value.asString());
247 }
248
249
250 string const tostr(LyXAlignment const & num)
251 {
252         switch (num) {
253         case LYX_ALIGN_NONE:
254                 return "none";
255         case LYX_ALIGN_BLOCK:
256                 return "block";
257         case LYX_ALIGN_LEFT:
258                 return "left";
259         case LYX_ALIGN_CENTER:
260                 return "center";
261         case LYX_ALIGN_RIGHT:
262                 return "right";
263         case LYX_ALIGN_LAYOUT:
264                 return "layout";
265         case LYX_ALIGN_SPECIAL:
266                 return "special";
267         }
268         return string();
269 }
270
271
272 string const tostr(Tabular::VAlignment const & num)
273 {
274         switch (num) {
275         case Tabular::LYX_VALIGN_TOP:
276                 return "top";
277         case Tabular::LYX_VALIGN_MIDDLE:
278                 return "middle";
279         case Tabular::LYX_VALIGN_BOTTOM:
280                 return "bottom";
281         }
282         return string();
283 }
284
285
286 string const tostr(Tabular::BoxType const & num)
287 {
288         switch (num) {
289         case Tabular::BOX_NONE:
290                 return "none";
291         case Tabular::BOX_PARBOX:
292                 return "parbox";
293         case Tabular::BOX_MINIPAGE:
294                 return "minipage";
295         }
296         return string();
297 }
298
299
300 // I would have liked a fromstr template a lot better. (Lgb)
301 bool string2type(string const str, LyXAlignment & num)
302 {
303         if (str == "none")
304                 num = LYX_ALIGN_NONE;
305         else if (str == "block")
306                 num = LYX_ALIGN_BLOCK;
307         else if (str == "left")
308                 num = LYX_ALIGN_LEFT;
309         else if (str == "center")
310                 num = LYX_ALIGN_CENTER;
311         else if (str == "right")
312                 num = LYX_ALIGN_RIGHT;
313         else
314                 return false;
315         return true;
316 }
317
318
319 bool string2type(string const str, Tabular::VAlignment & num)
320 {
321         if (str == "top")
322                 num = Tabular::LYX_VALIGN_TOP;
323         else if (str == "middle" )
324                 num = Tabular::LYX_VALIGN_MIDDLE;
325         else if (str == "bottom")
326                 num = Tabular::LYX_VALIGN_BOTTOM;
327         else
328                 return false;
329         return true;
330 }
331
332
333 bool string2type(string const str, Tabular::BoxType & num)
334 {
335         if (str == "none")
336                 num = Tabular::BOX_NONE;
337         else if (str == "parbox")
338                 num = Tabular::BOX_PARBOX;
339         else if (str == "minipage")
340                 num = Tabular::BOX_MINIPAGE;
341         else
342                 return false;
343         return true;
344 }
345
346
347 bool string2type(string const str, bool & num)
348 {
349         if (str == "true")
350                 num = true;
351         else if (str == "false")
352                 num = false;
353         else
354                 return false;
355         return true;
356 }
357
358
359 bool getTokenValue(string const & str, char const * token, string & ret)
360 {
361         ret.erase();
362         size_t token_length = strlen(token);
363         string::size_type pos = str.find(token);
364
365         if (pos == string::npos || pos + token_length + 1 >= str.length()
366                 || str[pos + token_length] != '=')
367                 return false;
368         pos += token_length + 1;
369         char ch = str[pos];
370         if (ch != '"' && ch != '\'') { // only read till next space
371                 ret += ch;
372                 ch = ' ';
373         }
374         while (pos < str.length() - 1 && str[++pos] != ch)
375                 ret += str[pos];
376
377         return true;
378 }
379
380
381 bool getTokenValue(string const & str, char const * token, docstring & ret)
382 {
383         string tmp;
384         bool const success = getTokenValue(str, token, tmp);
385         ret = from_utf8(tmp);
386         return success;
387 }
388
389
390 bool getTokenValue(string const & str, char const * token, int & num)
391 {
392         string tmp;
393         num = 0;
394         if (!getTokenValue(str, token, tmp))
395                 return false;
396         num = convert<int>(tmp);
397         return true;
398 }
399
400
401 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
402 {
403         string tmp;
404         return getTokenValue(str, token, tmp) && string2type(tmp, num);
405 }
406
407
408 bool getTokenValue(string const & str, char const * token,
409                                    Tabular::VAlignment & num)
410 {
411         string tmp;
412         return getTokenValue(str, token, tmp) && string2type(tmp, num);
413 }
414
415
416 bool getTokenValue(string const & str, char const * token,
417                                    Tabular::BoxType & num)
418 {
419         string tmp;
420         return getTokenValue(str, token, tmp) && string2type(tmp, num);
421 }
422
423
424 bool getTokenValue(string const & str, char const * token, bool & flag)
425 {
426         // set the flag always to false as this should be the default for bools
427         // not in the file-format.
428         flag = false;
429         string tmp;
430         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
431 }
432
433
434 bool getTokenValue(string const & str, char const * token, Length & len)
435 {
436         // set the length to be zero() as default as this it should be if not
437         // in the file format.
438         len = Length();
439         string tmp;
440         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
441 }
442
443
444 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
445 {
446         len = Length();
447         flag = false;
448         string tmp;
449         if (!getTokenValue(str, token, tmp))
450                 return false;
451         if (tmp == "default") {
452                 flag = true;
453                 return  true;
454         }
455         return isValidLength(tmp, &len);
456 }
457
458
459 void l_getline(istream & is, string & str)
460 {
461         str.erase();
462         while (str.empty()) {
463                 getline(is, str);
464                 if (!str.empty() && str[str.length() - 1] == '\r')
465                         str.erase(str.length() - 1);
466         }
467 }
468
469 } // namespace
470
471
472 string const featureAsString(Tabular::Feature feature)
473 {
474         TabularFeature * end = tabularFeature +
475                 sizeof(tabularFeature) / sizeof(TabularFeature);
476         TabularFeature * it = std::find_if(tabularFeature, end,
477                                            FeatureEqual(feature));
478         return (it == end) ? string() : it->feature;
479 }
480
481
482
483 /////////////////////////////////////////////////////////////////////
484 //
485 // Tabular
486 //
487 /////////////////////////////////////////////////////////////////////
488
489
490 Tabular::cellstruct::cellstruct(BufferParams const & bp)
491         : cellno(0),
492           width(0),
493           multicolumn(Tabular::CELL_NORMAL),
494           alignment(LYX_ALIGN_CENTER),
495           valignment(LYX_VALIGN_TOP),
496           top_line(true),
497           bottom_line(false),
498           left_line(true),
499           right_line(false),
500           usebox(BOX_NONE),
501           rotate(false),
502           inset(new InsetText(bp))
503 {}
504
505
506 Tabular::cellstruct::cellstruct(cellstruct const & cs)
507         : cellno(cs.cellno),
508           width(cs.width),
509           multicolumn(cs.multicolumn),
510           alignment(cs.alignment),
511           valignment(cs.valignment),
512           top_line(cs.top_line),
513           bottom_line(cs.bottom_line),
514           left_line(cs.left_line),
515           right_line(cs.right_line),
516           usebox(cs.usebox),
517           rotate(cs.rotate),
518           align_special(cs.align_special),
519           p_width(cs.p_width),
520           inset(dynamic_cast<InsetText*>(cs.inset->clone()))
521 {}
522
523
524 Tabular::cellstruct & Tabular::cellstruct::operator=(cellstruct cs)
525 {
526         swap(cs);
527         return *this;
528 }
529
530
531 void Tabular::cellstruct::swap(cellstruct & rhs)
532 {
533         std::swap(cellno, rhs.cellno);
534         std::swap(width, rhs.width);
535         std::swap(multicolumn, rhs.multicolumn);
536         std::swap(alignment, rhs.alignment);
537         std::swap(valignment, rhs.valignment);
538         std::swap(top_line, rhs.top_line);
539         std::swap(bottom_line, rhs.bottom_line);
540         std::swap(left_line, rhs.left_line);
541         std::swap(right_line, rhs.right_line);
542         std::swap(usebox, rhs.usebox);
543         std::swap(rotate, rhs.rotate);
544         std::swap(align_special, rhs.align_special);
545         p_width.swap(rhs.p_width);
546         inset.swap(rhs.inset);
547 }
548
549
550 Tabular::rowstruct::rowstruct()
551         : ascent(0),
552           descent(0),
553           top_line(true),
554           bottom_line(false),
555           top_space_default(false),
556           bottom_space_default(false),
557           interline_space_default(false),
558           endhead(false),
559           endfirsthead(false),
560           endfoot(false),
561           endlastfoot(false),
562           newpage(false)
563 {}
564
565
566 Tabular::columnstruct::columnstruct()
567         : alignment(LYX_ALIGN_CENTER),
568           valignment(LYX_VALIGN_TOP),
569           left_line(true),
570           right_line(false),
571           width(0)
572 {
573 }
574
575
576 Tabular::ltType::ltType()
577         : topDL(false),
578           bottomDL(false),
579           empty(false)
580 {}
581
582
583 Tabular::Tabular()
584 {
585         // unusable now!
586 }
587
588
589 Tabular::Tabular(BufferParams const & bp, row_type rows_arg,
590                        col_type columns_arg)
591 {
592         init(bp, rows_arg, columns_arg);
593 }
594
595
596 // activates all lines and sets all widths to 0
597 void Tabular::init(BufferParams const & bp, row_type rows_arg,
598                       col_type columns_arg)
599 {
600         row_info = row_vector(rows_arg);
601         column_info = column_vector(columns_arg);
602         cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, cellstruct(bp)));
603         row_info.reserve(10);
604         column_info.reserve(10);
605         cell_info.reserve(100);
606         fixCellNums();
607         for (row_type i = 0; i < rows_arg; ++i)
608                 cell_info[i].back().right_line = true;
609         row_info.back().bottom_line = true;
610         row_info.front().bottom_line = true;
611         column_info.back().right_line = true;
612         is_long_tabular = false;
613         rotate = false;
614         use_booktabs = false;
615 }
616
617
618 void Tabular::fixCellNums()
619 {
620         idx_type cellno = 0;
621         for (row_type i = 0; i < rowCount(); ++i) {
622                 for (col_type j = 0; j < columnCount(); ++j) {
623                         // When debugging it can be nice to set
624                         // this to true.
625                         cell_info[i][j].inset->setDrawFrame(false);
626                         cell_info[i][j].cellno = cellno++;
627                 }
628                 cell_info[i].back().right_line = true;
629         }
630
631         updateIndexes();
632 }
633
634
635 void Tabular::appendRow(BufferParams const & bp, idx_type const cell)
636 {
637         row_type const row = cellRow(cell);
638
639         row_vector::iterator rit = row_info.begin() + row;
640         row_info.insert(rit, rowstruct());
641         // now set the values of the row before
642         row_info[row] = row_info[row + 1];
643
644         row_type const nrows = rowCount();
645         col_type const ncols = columnCount();
646
647         cell_vvector old(nrows - 1);
648         for (row_type i = 0; i < nrows - 1; ++i)
649                 swap(cell_info[i], old[i]);
650
651         cell_info = cell_vvector(nrows, cell_vector(ncols, cellstruct(bp)));
652
653         for (row_type i = 0; i <= row; ++i)
654                 swap(cell_info[i], old[i]);
655         for (row_type i = row + 2; i < nrows; ++i)
656                 swap(cell_info[i], old[i - 1]);
657
658         if (bp.trackChanges)
659                 for (col_type j = 0; j < ncols; ++j)
660                         cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
661
662         updateIndexes();
663 }
664
665
666 void Tabular::deleteRow(row_type const row)
667 {
668         // Not allowed to delete last row
669         if (rowCount() == 1)
670                 return;
671
672         row_info.erase(row_info.begin() + row);
673         cell_info.erase(cell_info.begin() + row);
674         fixCellNums();
675 }
676
677
678 void Tabular::copyRow(BufferParams const & bp, row_type const row)
679 {
680         row_info.insert(row_info.begin() + row, row_info[row]);
681         cell_info.insert(cell_info.begin() + row, cell_info[row]);
682
683         if (bp.trackChanges)
684                 for (col_type j = 0; j < columnCount(); ++j)
685                         cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
686
687         updateIndexes();
688 }
689
690
691 void Tabular::appendColumn(BufferParams const & bp, idx_type const cell)
692 {
693         col_type const column = cellColumn(cell);
694         col_type const ncols = columnCount();
695         column_vector::iterator cit = column_info.begin() + column + 1;
696         column_info.insert(cit, columnstruct());
697         // set the column values of the column before
698         column_info[column + 1] = column_info[column];
699
700         for (row_type i = 0; i < rowCount(); ++i) {
701                 cell_info[i].insert(cell_info[i].begin() + column + 1, cellstruct(bp));
702
703                 // care about multicolumns
704                 if (cell_info[i][column + 1].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
705                         cell_info[i][column + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
706
707                 if (column + 2 >= ncols
708                     || cell_info[i][column + 2].multicolumn != CELL_PART_OF_MULTICOLUMN)
709                         cell_info[i][column + 1].multicolumn = Tabular::CELL_NORMAL;
710         }
711         //++column;
712         for (row_type i = 0; i < rowCount(); ++i) {
713                 cell_info[i][column + 1].inset->clear();
714                 if (bp.trackChanges)
715                         cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
716         }
717         fixCellNums();
718 }
719
720
721 void Tabular::deleteColumn(col_type const column)
722 {
723         // Not allowed to delete last column
724         if (columnCount() == 1)
725                 return;
726
727         column_info.erase(column_info.begin() + column);
728         for (row_type i = 0; i < rowCount(); ++i) {
729                 // Care about multicolumn cells
730                 if (column + 1 < columnCount() &&
731                     cell_info[i][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
732                     cell_info[i][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
733                         cell_info[i][column + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
734                 }
735                 cell_info[i].erase(cell_info[i].begin() + column);
736         }
737         fixCellNums();
738 }
739
740
741 void Tabular::copyColumn(BufferParams const & bp, col_type const column)
742 {
743         column_info.insert(column_info.begin() + column, column_info[column]);
744
745         for (row_type i = 0; i < rowCount(); ++i)
746                 cell_info[i].insert(cell_info[i].begin() + column, cell_info[i][column]);
747
748         if (bp.trackChanges)
749                 for (row_type i = 0; i < rowCount(); ++i)
750                         cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
751         fixCellNums();
752 }
753
754
755 void Tabular::updateIndexes()
756 {
757         numberofcells = 0;
758         // Count only non-multicol cells plus begin multicol
759         // cells, ignore non-begin multicol cells:
760         for (row_type row = 0; row < rowCount(); ++row) {
761                 for (col_type column = 0; column < columnCount(); ++column) {
762                         if (cell_info[row][column].multicolumn
763                                 != Tabular::CELL_PART_OF_MULTICOLUMN)
764                                 ++numberofcells;
765                         BOOST_ASSERT(numberofcells != 0);
766                         cell_info[row][column].cellno =
767                                 numberofcells - 1;
768                 }
769         }
770
771         rowofcell.resize(numberofcells);
772         columnofcell.resize(numberofcells);
773
774         row_type row = 0;
775         col_type column = 0;
776         for (idx_type c = 0;
777                  c < numberofcells && row < rowCount() && column < columnCount();) {
778                 rowofcell[c] = row;
779                 columnofcell[c] = column;
780                 ++c;
781                 do {
782                         ++column;
783                 } while (column < columnCount() &&
784                                  cell_info[row][column].multicolumn
785                                  == Tabular::CELL_PART_OF_MULTICOLUMN);
786
787                 if (column == columnCount()) {
788                         column = 0;
789                         ++row;
790                 }
791         }
792
793         for (row_type row = 0; row < rowCount(); ++row) {
794                 for (col_type column = 0; column < columnCount(); ++column) {
795                         if (isPartOfMultiColumn(row,column))
796                                 continue;
797                         cell_info[row][column].inset->setAutoBreakRows(
798                                 !getPWidth(cellIndex(row, column)).zero());
799                 }
800         }
801 }
802
803
804 Tabular::idx_type Tabular::cellCount() const
805 {
806         return numberofcells;
807 }
808
809
810 Tabular::idx_type Tabular::numberOfCellsInRow(idx_type const cell) const
811 {
812         row_type const row = cellRow(cell);
813         idx_type result = 0;
814         for (col_type i = 0; i < columnCount(); ++i)
815                 if (cell_info[row][i].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
816                         ++result;
817         return result;
818 }
819
820
821 bool Tabular::topLine(idx_type const cell, bool const wholerow) const
822 {
823         if (!wholerow && isMultiColumn(cell) &&
824             !(use_booktabs && cellRow(cell) == 0))
825                 return cellinfo_of_cell(cell).top_line;
826         return row_info[cellRow(cell)].top_line;
827 }
828
829
830 bool Tabular::bottomLine(idx_type const cell, bool wholerow) const
831 {
832         if (!wholerow && isMultiColumn(cell) &&
833             !(use_booktabs && isLastRow(cell)))
834                 return cellinfo_of_cell(cell).bottom_line;
835         return row_info[cellRow(cell)].bottom_line;
836 }
837
838
839 bool Tabular::leftLine(idx_type cell, bool wholecolumn) const
840 {
841         if (use_booktabs)
842                 return false;
843         if (!wholecolumn && isMultiColumn(cell) &&
844                 (isFirstCellInRow(cell) || isMultiColumn(cell-1)))
845                 return cellinfo_of_cell(cell).left_line;
846         return column_info[cellColumn(cell)].left_line;
847 }
848
849
850 bool Tabular::rightLine(idx_type cell, bool wholecolumn) const
851 {
852         if (use_booktabs)
853                 return false;
854         if (!wholecolumn && isMultiColumn(cell) &&
855                 (isLastCellInRow(cell) || isMultiColumn(cell + 1)))
856                 return cellinfo_of_cell(cell).right_line;
857         return column_info[cellRightColumn(cell)].right_line;
858 }
859
860
861 bool Tabular::topAlreadyDrawn(idx_type cell) const
862 {
863         row_type row = cellRow(cell);
864         if (row > 0 && !getAdditionalHeight(row)) {
865                 col_type column = cellColumn(cell);
866                 --row;
867                 while (column
868                            && cell_info[row][column].multicolumn
869                            == Tabular::CELL_PART_OF_MULTICOLUMN)
870                         --column;
871                 if (cell_info[row][column].multicolumn == Tabular::CELL_NORMAL)
872                         return row_info[row].bottom_line;
873                 else
874                         return cell_info[row][column].bottom_line;
875         }
876         return false;
877 }
878
879
880 bool Tabular::leftAlreadyDrawn(idx_type cell) const
881 {
882         col_type column = cellColumn(cell);
883         if (column > 0) {
884                 row_type row = cellRow(cell);
885                 while (--column &&
886                            (cell_info[row][column].multicolumn ==
887                                 Tabular::CELL_PART_OF_MULTICOLUMN)) { }
888                 if (getAdditionalWidth(cell_info[row][column].cellno))
889                         return false;
890                 return rightLine(cell_info[row][column].cellno);
891         }
892         return false;
893 }
894
895
896 bool Tabular::isLastRow(idx_type cell) const
897 {
898         return cellRow(cell) == rowCount() - 1;
899 }
900
901
902 int Tabular::getAdditionalHeight(row_type row) const
903 {
904         if (!row || row >= rowCount())
905                 return 0;
906
907         bool top = true;
908         bool bottom = true;
909
910         for (col_type column = 0; column < columnCount() && bottom; ++column) {
911                 switch (cell_info[row - 1][column].multicolumn) {
912                 case Tabular::CELL_BEGIN_OF_MULTICOLUMN:
913                         bottom = cell_info[row - 1][column].bottom_line;
914                         break;
915                 case Tabular::CELL_NORMAL:
916                         bottom = row_info[row - 1].bottom_line;
917                 }
918         }
919         for (col_type column = 0; column < columnCount() && top; ++column) {
920                 switch (cell_info[row][column].multicolumn) {
921                 case Tabular::CELL_BEGIN_OF_MULTICOLUMN:
922                         top = cell_info[row][column].top_line;
923                         break;
924                 case Tabular::CELL_NORMAL:
925                         top = row_info[row].top_line;
926                 }
927         }
928         int const interline_space = row_info[row - 1].interline_space_default ?
929                 default_line_space :
930                 row_info[row - 1].interline_space.inPixels(width());
931         if (top && bottom)
932                 return interline_space + WIDTH_OF_LINE;
933         return interline_space;
934 }
935
936
937 int Tabular::getAdditionalWidth(idx_type cell) const
938 {
939         // internally already set in setCellWidth
940         // used to get it back in text.cpp
941         col_type const col = cellRightColumn(cell);
942         row_type const row = cellRow(cell);
943         if (col < columnCount() - 1 && rightLine(cell) &&
944                 leftLine(cell_info[row][col+1].cellno)) // column_info[col+1].left_line)
945         {
946                 return WIDTH_OF_LINE;
947         }
948         return 0;
949 }
950
951
952 // returns the maximum over all rows
953 int Tabular::columnWidth(idx_type cell) const
954 {
955         col_type const column1 = cellColumn(cell);
956         col_type const column2 = cellRightColumn(cell);
957         int result = 0;
958         for (col_type i = column1; i <= column2; ++i)
959                 result += column_info[i].width;
960         return result;
961 }
962
963
964 int Tabular::width() const
965 {
966         int width = 0;
967         for (col_type i = 0; i < columnCount(); ++i)
968                 width += column_info[i].width;
969         return width;
970 }
971
972
973 // returns true if a complete update is necessary, otherwise false
974 bool Tabular::setWidthOfMulticolCell(idx_type cell, int new_width)
975 {
976         if (!isMultiColumn(cell))
977                 return false;
978
979         row_type const row = cellRow(cell);
980         col_type const column1 = cellColumn(cell);
981         col_type const column2 = cellRightColumn(cell);
982         int const old_val = cell_info[row][column2].width;
983
984         // first set columns to 0 so we can calculate the right width
985         for (col_type i = column1; i <= column2; ++i) {
986                 cell_info[row][i].width = 0;
987         }
988         // set the width to MAX_WIDTH until width > 0
989         int width = new_width + 2 * WIDTH_OF_LINE;
990         col_type i = column1;
991         for (; i < column2 && width > column_info[i].width; ++i) {
992                 cell_info[row][i].width = column_info[i].width;
993                 width -= column_info[i].width;
994         }
995         if (width > 0) {
996                 cell_info[row][i].width = width;
997         }
998         if (old_val != cell_info[row][column2].width) {
999                 // in this case we have to recalculate all multicolumn cells which
1000                 // have this column as one of theirs but not as last one
1001                 calculate_width_of_column_NMC(i);
1002                 recalculateMulticolumnsOfColumn(i);
1003                 calculate_width_of_column(i);
1004         }
1005         return true;
1006 }
1007
1008
1009 void Tabular::recalculateMulticolumnsOfColumn(col_type column)
1010 {
1011         // the last column does not have to be recalculated because all
1012         // multicolumns will have here there last multicolumn cell which
1013         // always will have the whole rest of the width of the cell.
1014         if (columnCount() < 2 || column > (columnCount() - 2))
1015                 return;
1016         for (row_type row = 0; row < rowCount(); ++row) {
1017                 int mc = cell_info[row][column].multicolumn;
1018                 int nmc = cell_info[row][column+1].multicolumn;
1019                 // we only have to update multicolumns which do not have this
1020                 // column as their last column!
1021                 if (mc == CELL_BEGIN_OF_MULTICOLUMN ||
1022                           (mc == CELL_PART_OF_MULTICOLUMN &&
1023                            nmc == CELL_PART_OF_MULTICOLUMN))
1024                 {
1025                         idx_type const cellno = cell_info[row][column].cellno;
1026                         setWidthOfMulticolCell(cellno,
1027                                                cellWidth(cellno) - 2 * WIDTH_OF_LINE);
1028                 }
1029         }
1030 }
1031
1032
1033 void Tabular::setCellWidth(idx_type cell, int new_width)
1034 {
1035         row_type const row = cellRow(cell);
1036         col_type const column1 = cellColumn(cell);
1037         bool tmp = false;
1038         int width = 0;
1039         int add_width = 0;
1040
1041         if (rightLine(cell_info[row][column1].cellno, true) &&
1042                 column1 < columnCount() - 1 &&
1043                 leftLine(cell_info[row][column1+1].cellno, true))
1044         {
1045                 add_width = WIDTH_OF_LINE;
1046         }
1047
1048         if (cellWidth(cell) == new_width + 2 * WIDTH_OF_LINE + add_width)
1049                 return;
1050
1051         if (isMultiColumnReal(cell)) {
1052                 tmp = setWidthOfMulticolCell(cell, new_width);
1053         } else {
1054                 width = new_width + 2 * WIDTH_OF_LINE + add_width;
1055                 cell_info[row][column1].width = width;
1056                 tmp = calculate_width_of_column_NMC(column1);
1057                 if (tmp)
1058                         recalculateMulticolumnsOfColumn(column1);
1059         }
1060         if (tmp) {
1061                 for (col_type i = 0; i < columnCount(); ++i)
1062                         calculate_width_of_column(i);
1063         }
1064 }
1065
1066
1067 void Tabular::setAlignment(idx_type cell, LyXAlignment align,
1068                               bool onlycolumn)
1069 {
1070         if (!isMultiColumn(cell) || onlycolumn)
1071                 column_info[cellColumn(cell)].alignment = align;
1072         if (!onlycolumn)
1073                 cellinfo_of_cell(cell).alignment = align;
1074 }
1075
1076
1077 void Tabular::setVAlignment(idx_type cell, VAlignment align,
1078                                bool onlycolumn)
1079 {
1080         if (!isMultiColumn(cell) || onlycolumn)
1081                 column_info[cellColumn(cell)].valignment = align;
1082         if (!onlycolumn)
1083                 cellinfo_of_cell(cell).valignment = align;
1084 }
1085
1086
1087 namespace {
1088
1089 /**
1090  * Allow line and paragraph breaks for fixed width cells or disallow them,
1091  * merge cell paragraphs and reset layout to standard for variable width
1092  * cells.
1093  */
1094 void toggleFixedWidth(Cursor & cur, InsetText * inset, bool fixedWidth)
1095 {
1096         inset->setAutoBreakRows(fixedWidth);
1097         if (fixedWidth)
1098                 return;
1099
1100         // merge all paragraphs to one
1101         BufferParams const & bp = cur.bv().buffer().params();
1102         while (inset->paragraphs().size() > 1)
1103                 mergeParagraph(bp, inset->paragraphs(), 0);
1104
1105         // reset layout
1106         cur.push(*inset);
1107         // undo information has already been recorded
1108         inset->getText(0)->setLayout(cur.bv().buffer(), 0, cur.lastpit() + 1,
1109                         bp.getTextClass().defaultLayoutName());
1110         cur.pop();
1111 }
1112
1113 }
1114
1115
1116 void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
1117                 Length const & width)
1118 {
1119         col_type const j = cellColumn(cell);
1120
1121         column_info[j].p_width = width;
1122         for (row_type i = 0; i < rowCount(); ++i) {
1123                 idx_type const cell = cellIndex(i, j);
1124                 // because of multicolumns
1125                 toggleFixedWidth(cur, getCellInset(cell).get(),
1126                                  !getPWidth(cell).zero());
1127         }
1128         // cur paragraph can become invalid after paragraphs were merged
1129         if (cur.pit() > cur.lastpit())
1130                 cur.pit() = cur.lastpit();
1131         // cur position can become invalid after newlines were removed
1132         if (cur.pos() > cur.lastpos())
1133                 cur.pos() = cur.lastpos();
1134 }
1135
1136
1137 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
1138                 Length const & width)
1139 {
1140         if (!isMultiColumn(cell))
1141                 return false;
1142
1143         cellinfo_of_cell(cell).p_width = width;
1144         toggleFixedWidth(cur, getCellInset(cell).get(), !width.zero());
1145         // cur paragraph can become invalid after paragraphs were merged
1146         if (cur.pit() > cur.lastpit())
1147                 cur.pit() = cur.lastpit();
1148         // cur position can become invalid after newlines were removed
1149         if (cur.pos() > cur.lastpos())
1150                 cur.pos() = cur.lastpos();
1151         return true;
1152 }
1153
1154
1155 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
1156                                  Tabular::Feature what)
1157 {
1158         if (what == SET_SPECIAL_MULTI)
1159                 cellinfo_of_cell(cell).align_special = special;
1160         else
1161                 column_info[cellColumn(cell)].align_special = special;
1162 }
1163
1164
1165 void Tabular::setAllLines(idx_type cell, bool line)
1166 {
1167         setTopLine(cell, line);
1168         setBottomLine(cell, line);
1169         setRightLine(cell, line);
1170         setLeftLine(cell, line);
1171 }
1172
1173
1174 void Tabular::setTopLine(idx_type cell, bool line, bool wholerow)
1175 {
1176         row_type const row = cellRow(cell);
1177         if (wholerow || !isMultiColumn(cell))
1178                 row_info[row].top_line = line;
1179         else
1180                 cellinfo_of_cell(cell).top_line = line;
1181 }
1182
1183
1184 void Tabular::setBottomLine(idx_type cell, bool line, bool wholerow)
1185 {
1186         if (wholerow || !isMultiColumn(cell))
1187                 row_info[cellRow(cell)].bottom_line = line;
1188         else
1189                 cellinfo_of_cell(cell).bottom_line = line;
1190 }
1191
1192
1193 void Tabular::setLeftLine(idx_type cell, bool line, bool wholecolumn)
1194 {
1195         if (wholecolumn || !isMultiColumn(cell))
1196                 column_info[cellColumn(cell)].left_line = line;
1197         else
1198                 cellinfo_of_cell(cell).left_line = line;
1199 }
1200
1201
1202 void Tabular::setRightLine(idx_type cell, bool line, bool wholecolumn)
1203 {
1204         if (wholecolumn || !isMultiColumn(cell))
1205                 column_info[cellRightColumn(cell)].right_line = line;
1206         else
1207                 cellinfo_of_cell(cell).right_line = line;
1208 }
1209
1210
1211 LyXAlignment Tabular::getAlignment(idx_type cell, bool onlycolumn) const
1212 {
1213         if (!onlycolumn && isMultiColumn(cell))
1214                 return cellinfo_of_cell(cell).alignment;
1215         return column_info[cellColumn(cell)].alignment;
1216 }
1217
1218
1219 Tabular::VAlignment
1220 Tabular::getVAlignment(idx_type cell, bool onlycolumn) const
1221 {
1222         if (!onlycolumn && isMultiColumn(cell))
1223                 return cellinfo_of_cell(cell).valignment;
1224         return column_info[cellColumn(cell)].valignment;
1225 }
1226
1227
1228 Length const Tabular::getPWidth(idx_type cell) const
1229 {
1230         if (isMultiColumn(cell))
1231                 return cellinfo_of_cell(cell).p_width;
1232         return column_info[cellColumn(cell)].p_width;
1233 }
1234
1235
1236 Length const Tabular::getColumnPWidth(idx_type cell) const
1237 {
1238         return column_info[cellColumn(cell)].p_width;
1239 }
1240
1241
1242 Length const Tabular::getMColumnPWidth(idx_type cell) const
1243 {
1244         if (isMultiColumn(cell))
1245                 return cellinfo_of_cell(cell).p_width;
1246         return Length();
1247 }
1248
1249
1250 docstring const Tabular::getAlignSpecial(idx_type cell, int what) const
1251 {
1252         if (what == SET_SPECIAL_MULTI)
1253                 return cellinfo_of_cell(cell).align_special;
1254         return column_info[cellColumn(cell)].align_special;
1255 }
1256
1257
1258 int Tabular::cellWidth(idx_type cell) const
1259 {
1260         row_type const row = cellRow(cell);
1261         col_type const column1 = cellColumn(cell);
1262         col_type const column2 = cellRightColumn(cell);
1263         int result = 0;
1264         for (col_type i = column1; i <= column2; ++i)
1265                 result += cell_info[row][i].width;
1266         return result;
1267 }
1268
1269
1270 int Tabular::getBeginningOfTextInCell(idx_type cell) const
1271 {
1272         int x = 0;
1273
1274         switch (getAlignment(cell)) {
1275         case LYX_ALIGN_CENTER:
1276                 x += (columnWidth(cell) - cellWidth(cell)) / 2;
1277                 break;
1278         case LYX_ALIGN_RIGHT:
1279                 x += columnWidth(cell) - cellWidth(cell);
1280                 // + getAdditionalWidth(cell);
1281                 break;
1282         default:
1283                 // LYX_ALIGN_LEFT: nothing :-)
1284                 break;
1285         }
1286
1287         // the LaTeX Way :-(
1288         x += WIDTH_OF_LINE;
1289         return x;
1290 }
1291
1292
1293 bool Tabular::isFirstCellInRow(idx_type cell) const
1294 {
1295         return cellColumn(cell) == 0;
1296 }
1297
1298
1299 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
1300 {
1301         if (row > rowCount() - 1)
1302                 row = rowCount() - 1;
1303         return cell_info[row][0].cellno;
1304 }
1305
1306
1307 bool Tabular::isLastCellInRow(idx_type cell) const
1308 {
1309         return cellRightColumn(cell) == columnCount() - 1;
1310 }
1311
1312
1313 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
1314 {
1315         if (row > rowCount() - 1)
1316                 row = rowCount() - 1;
1317         return cell_info[row][columnCount() - 1].cellno;
1318 }
1319
1320
1321 void Tabular::calculate_width_of_column(col_type column)
1322 {
1323         int maximum = 0;
1324         for (row_type i = 0; i < rowCount(); ++i)
1325                 maximum = max(cell_info[i][column].width, maximum);
1326         column_info[column].width = maximum;
1327 }
1328
1329
1330 //
1331 // Calculate the columns regarding ONLY the normal cells and if this
1332 // column is inside a multicolumn cell then use it only if its the last
1333 // column of this multicolumn cell as this gives an added width to the
1334 // column, all the rest should be adapted!
1335 //
1336 bool Tabular::calculate_width_of_column_NMC(col_type column)
1337 {
1338         int const old_column_width = column_info[column].width;
1339         int max = 0;
1340         for (row_type i = 0; i < rowCount(); ++i) {
1341                 idx_type cell = cellIndex(i, column);
1342                 bool ismulti = isMultiColumnReal(cell);
1343                 if ((!ismulti || column == cellRightColumn(cell)) &&
1344                         cell_info[i][column].width > max)
1345                 {
1346                         max = cell_info[i][column].width;
1347                 }
1348         }
1349         column_info[column].width = max;
1350         return column_info[column].width != old_column_width;
1351 }
1352
1353
1354 Tabular::row_type Tabular::cellRow(idx_type cell) const
1355 {
1356         if (cell >= cellCount())
1357                 return rowCount() - 1;
1358         if (cell == npos)
1359                 return 0;
1360         return rowofcell[cell];
1361 }
1362
1363
1364 Tabular::col_type Tabular::cellColumn(idx_type cell) const
1365 {
1366         if (cell >= cellCount())
1367                 return columnCount() - 1;
1368         if (cell == npos)
1369                 return 0;
1370         return columnofcell[cell];
1371 }
1372
1373
1374 Tabular::col_type Tabular::cellRightColumn(idx_type cell) const
1375 {
1376         row_type const row = cellRow(cell);
1377         col_type column = cellColumn(cell);
1378         while (column < columnCount() - 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", rowCount())
1391            << write_attribute("columns", columnCount())
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 < columnCount(); ++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 < rowCount(); ++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 < columnCount(); ++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 < columnCount(); ++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 < rowCount(); ++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 < columnCount(); ++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         updateIndexes();
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 cellColumn(cell) != cellRightColumn(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[cellRow(cell)][cellColumn(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[cellColumn(cell)].alignment;
1614         cs.top_line = row_info[cellRow(cell)].top_line;
1615         cs.bottom_line = row_info[cellRow(cell)].bottom_line;
1616         cs.left_line = column_info[cellColumn(cell)].left_line;
1617         cs.right_line = column_info[cellColumn(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         updateIndexes();
1625 }
1626
1627
1628 Tabular::idx_type Tabular::cells_in_multicolumn(idx_type cell) const
1629 {
1630         row_type const row = cellRow(cell);
1631         col_type column = cellColumn(cell);
1632         idx_type result = 1;
1633         ++column;
1634         while (column < columnCount() &&
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 = cellRow(cell);
1647         col_type column = cellColumn(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 < columnCount() &&
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         updateIndexes();
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 < rowCount(); ++i)
1720                 for (col_type j = 0; j < columnCount(); ++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 < cellCount())
1730                 return false;
1731         return true;
1732 }
1733
1734
1735 Tabular::idx_type Tabular::getCellAbove(idx_type cell) const
1736 {
1737         if (cellRow(cell) > 0)
1738                 return cell_info[cellRow(cell)-1][cellColumn(cell)].cellno;
1739         return cell;
1740 }
1741
1742
1743 Tabular::idx_type Tabular::getCellBelow(idx_type cell) const
1744 {
1745         if (cellRow(cell) + 1 < rowCount())
1746                 return cell_info[cellRow(cell)+1][cellColumn(cell)].cellno;
1747         return cell;
1748 }
1749
1750
1751 Tabular::idx_type Tabular::getLastCellAbove(idx_type cell) const
1752 {
1753         if (cellRow(cell) == 0)
1754                 return cell;
1755         if (!isMultiColumn(cell))
1756                 return getCellAbove(cell);
1757         return cell_info[cellRow(cell) - 1][cellRightColumn(cell)].cellno;
1758 }
1759
1760
1761 Tabular::idx_type Tabular::getLastCellBelow(idx_type cell) const
1762 {
1763         if (cellRow(cell) + 1 >= rowCount())
1764                 return cell;
1765         if (!isMultiColumn(cell))
1766                 return getCellBelow(cell);
1767         return cell_info[cellRow(cell) + 1][cellRightColumn(cell)].cellno;
1768 }
1769
1770
1771 Tabular::idx_type Tabular::cellIndex(row_type row,
1772                                                col_type column) const
1773 {
1774         BOOST_ASSERT(column != npos && column < columnCount() &&
1775                      row    != npos && row    < rowCount());
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[cellColumn(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 < rowCount(); ++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 < rowCount(); ++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 < rowCount(); ++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 < rowCount(); ++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::setRowAscent(row_type row, int height)
1917 {
1918         if (row >= rowCount() || row_info[row].ascent == height)
1919                 return;
1920         row_info[row].ascent = height;
1921 }
1922
1923
1924 void Tabular::setRowDescent(row_type row, int height)
1925 {
1926         if (row >= rowCount() || row_info[row].descent == height)
1927                 return;
1928         row_info[row].descent = height;
1929 }
1930
1931
1932 int Tabular::rowAscent(row_type row) const
1933 {
1934         if (row >= rowCount())
1935                 return 0;
1936         return row_info[row].ascent;
1937 }
1938
1939
1940 int Tabular::rowDescent(row_type row) const
1941 {
1942         BOOST_ASSERT(row < rowCount());
1943         return row_info[row].descent;
1944 }
1945
1946
1947 int Tabular::height() const
1948 {
1949         int height = 0;
1950         for (row_type row = 0; row < rowCount(); ++row)
1951                 height += rowAscent(row) + rowDescent(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 < rowCount());
1960         BOOST_ASSERT(column < columnCount());
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 < rowCount());
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                                    << cellColumn(i) + 1
1988                                    << '-'
1989                                    << cellRightColumn(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 >= rowCount())
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 == rowCount() - 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                                    << cellColumn(i) + 1
2024                                    << '-'
2025                                    << cellRightColumn(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) < cellCount()) && !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 < rowCount(); ++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 < rowCount(); ++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 < rowCount(); ++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 < rowCount(); ++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 = cellIndex(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 < columnCount(); ++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.isRTL(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 < columnCount(); ++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 < rowCount(); ++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 < columnCount(); ++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=\"" << columnCount()
2511            << "\" colsep=\"1\" rowsep=\"1\">\n";
2512
2513         for (col_type i = 0; i < columnCount(); ++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 < rowCount(); ++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 < rowCount(); ++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 < rowCount(); ++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 = cellColumn(i);
2615                 int len = clen[column];
2616                 while (column < columnCount() - 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 = cellColumn(i);
2663                 int len = clen[column];
2664                 while (column < columnCount() -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 < columnCount() -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, char_type delim) const
2736 {
2737         // first calculate the width of the single columns
2738         vector<unsigned int> clen(columnCount());
2739
2740         if (!onlydata) {
2741                 // first all non (real) multicolumn cells!
2742                 for (col_type j = 0; j < columnCount(); ++j) {
2743                         clen[j] = 0;
2744                         for (row_type i = 0; i < rowCount(); ++i) {
2745                                 idx_type cell = cellIndex(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 < columnCount(); ++j) {
2756                         for (row_type i = 0; i < rowCount(); ++i) {
2757                                 idx_type cell = cellIndex(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 < rowCount(); ++i) {
2773                 if (!onlydata && plaintextTopHLine(os, i, clen))
2774                         os << docstring(depth * 2, ' ');
2775                 for (col_type j = 0; j < columnCount(); ++j) {
2776                         if (isPartOfMultiColumn(i, j))
2777                                 continue;
2778                         if (onlydata && j > 0)
2779                                 // we don't use operator<< for single UCS4 character.
2780                                 // see explanation in docstream.h
2781                                 os.put(delim);
2782                         plaintextPrintCell(buf, os, runparams,
2783                                            cell, i, j, clen, onlydata);
2784                         ++cell;
2785                 }
2786                 os << endl;
2787                 if (!onlydata) {
2788                         os << docstring(depth * 2, ' ');
2789                         if (plaintextBottomHLine(os, i, clen))
2790                                 os << docstring(depth * 2, ' ');
2791                 }
2792         }
2793 }
2794
2795
2796 shared_ptr<InsetText> Tabular::getCellInset(idx_type cell) const
2797 {
2798         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2799 }
2800
2801
2802 shared_ptr<InsetText> Tabular::getCellInset(row_type row,
2803                                                col_type column) const
2804 {
2805         return cell_info[row][column].inset;
2806 }
2807
2808
2809 void Tabular::setCellInset(row_type row, col_type column,
2810                               shared_ptr<InsetText> ins) const
2811 {
2812         cell_info[row][column].inset = ins;
2813 }
2814
2815
2816 Tabular::idx_type
2817 Tabular::getCellFromInset(Inset const * inset) const
2818 {
2819         // is this inset part of the tabular?
2820         if (!inset) {
2821                 lyxerr << "Error: this is not a cell of the tabular!" << endl;
2822                 BOOST_ASSERT(false);
2823         }
2824
2825         for (idx_type cell = 0, n = cellCount(); cell < n; ++cell)
2826                 if (getCellInset(cell).get() == inset) {
2827                         LYXERR(Debug::INSETTEXT, "Tabular::getCellFromInset: "
2828                                 << "cell=" << cell);
2829                         return cell;
2830                 }
2831
2832         // We should have found a cell at this point
2833         lyxerr << "Tabular::getCellFromInset: Cell of inset "
2834                 << inset << " not found!" << endl;
2835         BOOST_ASSERT(false);
2836         // shut up compiler
2837         return 0;
2838 }
2839
2840
2841 void Tabular::validate(LaTeXFeatures & features) const
2842 {
2843         features.require("NeedTabularnewline");
2844         if (useBookTabs())
2845                 features.require("booktabs");
2846         if (isLongTabular())
2847                 features.require("longtable");
2848         if (needRotating())
2849                 features.require("rotating");
2850         for (idx_type cell = 0; cell < cellCount(); ++cell) {
2851                 if (getVAlignment(cell) != LYX_VALIGN_TOP ||
2852                      (!getPWidth(cell).zero() && !isMultiColumn(cell)))
2853                         features.require("array");
2854                 getCellInset(cell)->validate(features);
2855         }
2856 }
2857
2858
2859 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2860 {
2861         ParagraphList const & parlist = getCellInset(cell)->paragraphs();
2862         ParagraphList::const_iterator cit = parlist.begin();
2863         ParagraphList::const_iterator end = parlist.end();
2864
2865         for (; cit != end; ++cit)
2866                 for (int i = 0; i < cit->size(); ++i)
2867                         if (cit->isNewline(i))
2868                                 return BOX_PARBOX;
2869
2870         return BOX_NONE;
2871 }
2872
2873
2874 /////////////////////////////////////////////////////////////////////
2875 //
2876 // InsetTabular
2877 //
2878 /////////////////////////////////////////////////////////////////////
2879
2880 InsetTabular::InsetTabular(Buffer const & buf, row_type rows,
2881                            col_type columns)
2882         : tabular(buf.params(), max(rows, row_type(1)),
2883           max(columns, col_type(1))), buffer_(&buf), scx_(0)
2884 {}
2885
2886
2887 InsetTabular::InsetTabular(InsetTabular const & tab)
2888         : Inset(tab), tabular(tab.tabular),
2889                 buffer_(tab.buffer_), scx_(0)
2890 {}
2891
2892
2893 InsetTabular::~InsetTabular()
2894 {
2895         InsetTabularMailer(*this).hideDialog();
2896 }
2897
2898
2899 Inset * InsetTabular::clone() const
2900 {
2901         return new InsetTabular(*this);
2902 }
2903
2904
2905 Buffer const & InsetTabular::buffer() const
2906 {
2907         return *buffer_;
2908 }
2909
2910
2911 void InsetTabular::buffer(Buffer const * b)
2912 {
2913         buffer_ = b;
2914 }
2915
2916
2917 void InsetTabular::write(Buffer const & buf, ostream & os) const
2918 {
2919         os << "Tabular" << endl;
2920         tabular.write(buf, os);
2921 }
2922
2923
2924 void InsetTabular::read(Buffer const & buf, Lexer & lex)
2925 {
2926         bool const old_format = (lex.getString() == "\\LyXTable");
2927
2928         tabular.read(buf, lex);
2929
2930         if (old_format)
2931                 return;
2932
2933         lex.next();
2934         string token = lex.getString();
2935         while (lex && token != "\\end_inset") {
2936                 lex.next();
2937                 token = lex.getString();
2938         }
2939         if (!lex) {
2940                 lex.printError("Missing \\end_inset at this point. "
2941                                "Read: `$$Token'");
2942         }
2943 }
2944
2945
2946 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
2947 {
2948         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
2949         //      mi.base.textwidth << "\n";
2950         if (!mi.base.bv) {
2951                 lyxerr << "InsetTabular::metrics: need bv" << endl;
2952                 BOOST_ASSERT(false);
2953         }
2954
2955         row_type i = 0;
2956         for (idx_type cell = 0; i < tabular.rowCount(); ++i) {
2957                 int maxAsc = 0;
2958                 int maxDesc = 0;
2959                 for (col_type j = 0; j < tabular.columnCount(); ++j) {
2960                         if (tabular.isPartOfMultiColumn(i, j))
2961                                 // Multicolumn cell, but not first one
2962                                 continue;
2963                         Dimension dim;
2964                         MetricsInfo m = mi;
2965                         Length p_width;
2966                         if (tabular.cell_info[i][j].multicolumn ==
2967                             Tabular::CELL_BEGIN_OF_MULTICOLUMN)
2968                                 p_width = tabular.cellinfo_of_cell(cell).p_width;
2969                         else
2970                                 p_width = tabular.column_info[j].p_width;
2971                         if (!p_width.zero())
2972                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
2973                         tabular.getCellInset(cell)->metrics(m, dim);
2974                         if (!p_width.zero())
2975                                 dim.wid = m.base.textwidth;
2976                         tabular.setCellWidth(cell, dim.wid);
2977                         if (p_width.zero()) {
2978                                 m.base.textwidth = dim.wid + 2 * ADD_TO_TABULAR_WIDTH;
2979                                 // FIXME there must be a way to get rid of
2980                                 // the second metrics call
2981                                 tabular.getCellInset(cell)->metrics(m, dim);
2982                         }
2983                         maxAsc  = max(maxAsc, dim.asc);
2984                         maxDesc = max(maxDesc, dim.des);
2985                         ++cell;
2986                 }
2987                 int const top_space = tabular.row_info[i].top_space_default ?
2988                         default_line_space :
2989                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
2990                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
2991                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
2992                         default_line_space :
2993                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
2994                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
2995         }
2996
2997         dim.asc = tabular.rowAscent(0);
2998         dim.des = tabular.height() - dim.asc;
2999         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3000 }
3001
3002
3003 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3004 {
3005         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
3006         BufferView * bv = pi.base.bv;
3007
3008         // FIXME: As the full backrgound is painted in drawSelection(),
3009         // we have no choice but to do a full repaint for the Text cells.
3010         pi.full_repaint = true;
3011
3012         resetPos(bv->cursor());
3013
3014         x += scx_;
3015         x += ADD_TO_TABULAR_WIDTH;
3016
3017         bool const original_drawing_state = pi.pain.isDrawingEnabled();
3018
3019         idx_type idx = 0;
3020         first_visible_cell = Tabular::npos;
3021         for (row_type i = 0; i < tabular.rowCount(); ++i) {
3022                 int nx = x;
3023                 int const a = tabular.rowAscent(i);
3024                 int const d = tabular.rowDescent(i);
3025                 idx = tabular.cellIndex(i, 0);
3026                 for (col_type j = 0; j < tabular.columnCount(); ++j) {
3027                         if (tabular.isPartOfMultiColumn(i, j))
3028                                 continue;
3029                         if (first_visible_cell == Tabular::npos)
3030                                 first_visible_cell = idx;
3031
3032                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
3033                         // Cache the Inset position.
3034                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
3035                         if (nx + tabular.columnWidth(idx) < 0
3036                             || nx > bv->workWidth()
3037                             || y + d < 0
3038                             || y - a > bv->workHeight()) {
3039                                 pi.pain.setDrawingEnabled(false);
3040                                 cell(idx)->draw(pi, cx, y);
3041                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
3042                                 pi.pain.setDrawingEnabled(original_drawing_state);
3043                         } else {
3044                                 cell(idx)->draw(pi, cx, y);
3045                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
3046                         }
3047                         nx += tabular.columnWidth(idx);
3048                         ++idx;
3049                 }
3050
3051                 if (i + 1 < tabular.rowCount())
3052                         y += d + tabular.rowAscent(i + 1) +
3053                                 tabular.getAdditionalHeight(i + 1);
3054         }
3055 }
3056
3057
3058 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3059 {
3060         Cursor & cur = pi.base.bv->cursor();
3061
3062         x += scx_ + ADD_TO_TABULAR_WIDTH;
3063
3064         // FIXME: it is wrong to completely paint the background
3065         // if we want to do single row painting.
3066
3067         // Paint background of current tabular
3068         int const w = tabular.width();
3069         int const h = tabular.height();
3070         int yy = y - tabular.rowAscent(0);
3071         pi.pain.fillRectangle(x, yy, w, h, backgroundColor());
3072
3073         if (!cur.selection())
3074                 return;
3075         if (&cur.inset() != this)
3076                 return;
3077
3078         //resetPos(cur);
3079
3080
3081         if (tablemode(cur)) {
3082                 row_type rs, re;
3083                 col_type cs, ce;
3084                 getSelection(cur, rs, re, cs, ce);
3085                 y -= tabular.rowAscent(0);
3086                 for (row_type j = 0; j < tabular.rowCount(); ++j) {
3087                         int const a = tabular.rowAscent(j);
3088                         int const h = a + tabular.rowDescent(j);
3089                         int xx = x;
3090                         y += tabular.getAdditionalHeight(j);
3091                         for (col_type i = 0; i < tabular.columnCount(); ++i) {
3092                                 if (tabular.isPartOfMultiColumn(j, i))
3093                                         continue;
3094                                 idx_type const cell =
3095                                         tabular.cellIndex(j, i);
3096                                 int const w = tabular.columnWidth(cell);
3097                                 if (i >= cs && i <= ce && j >= rs && j <= re)
3098                                         pi.pain.fillRectangle(xx, y, w, h,
3099                                                               Color_selection);
3100                                 xx += w;
3101                         }
3102                         y += h;
3103                 }
3104
3105         } else {
3106                 x += getCellXPos(cur.idx());
3107                 x += tabular.getBeginningOfTextInCell(cur.idx());
3108                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3109         }
3110 }
3111
3112
3113 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3114                                  row_type row, idx_type cell, bool erased) const
3115 {
3116         int x2 = x + tabular.columnWidth(cell);
3117         bool on_off = false;
3118         ColorCode col = Color_tabularline;
3119         ColorCode onoffcol = Color_tabularonoffline;
3120
3121         if (erased) {
3122                 col = Color_deletedtext;
3123                 onoffcol = Color_deletedtext;
3124         }
3125
3126         if (!tabular.topAlreadyDrawn(cell)) {
3127                 on_off = !tabular.topLine(cell);
3128                 pain.line(x, y - tabular.rowAscent(row),
3129                           x2, y -  tabular.rowAscent(row),
3130                           on_off ? onoffcol : col,
3131                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3132         }
3133         on_off = !tabular.bottomLine(cell);
3134         pain.line(x, y + tabular.rowDescent(row),
3135                   x2, y + tabular.rowDescent(row),
3136                   on_off ? onoffcol : col,
3137                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3138         if (!tabular.leftAlreadyDrawn(cell)) {
3139                 on_off = !tabular.leftLine(cell);
3140                 pain.line(x, y -  tabular.rowAscent(row),
3141                           x, y +  tabular.rowDescent(row),
3142                           on_off ? onoffcol : col,
3143                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3144         }
3145         on_off = !tabular.rightLine(cell);
3146         pain.line(x2 - tabular.getAdditionalWidth(cell),
3147                   y -  tabular.rowAscent(row),
3148                   x2 - tabular.getAdditionalWidth(cell),
3149                   y +  tabular.rowDescent(row),
3150                   on_off ? onoffcol : col,
3151                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3152 }
3153
3154
3155 docstring const InsetTabular::editMessage() const
3156 {
3157         return _("Opened table");
3158 }
3159
3160
3161 void InsetTabular::edit(Cursor & cur, bool left)
3162 {
3163         //lyxerr << "InsetTabular::edit: " << this << endl;
3164         cur.finishUndo();
3165         cur.selection() = false;
3166         cur.push(*this);
3167         if (left) {
3168                 if (isRightToLeft(cur))
3169                         cur.idx() = tabular.getLastCellInRow(0);
3170                 else
3171                         cur.idx() = 0;
3172                 cur.pit() = 0;
3173                 cur.pos() = 0;
3174         } else {
3175                 if (isRightToLeft(cur))
3176                         cur.idx() = tabular.getFirstCellInRow(tabular.rowCount() - 1);
3177                 else
3178                         cur.idx() = tabular.cellCount() - 1;
3179                 cur.pit() = 0;
3180                 cur.pos() = cur.lastpos(); // FIXME crude guess
3181         }
3182         // FIXME: this accesses the position cache before it is initialized
3183         //resetPos(cur);
3184         //cur.bv().fitCursor();
3185 }
3186
3187
3188 void InsetTabular::updateLabels(Buffer const & buf, ParIterator const & it)
3189 {
3190         // In a longtable, tell captions what the current float is
3191         Counters & cnts = buf.params().getTextClass().counters();
3192         string const saveflt = cnts.current_float();
3193         if (tabular.isLongTabular())
3194                 cnts.current_float("table");
3195
3196         ParIterator it2 = it;
3197         it2.forwardPos();
3198         size_t const end = it2.nargs();
3199         for ( ; it2.idx() < end; it2.top().forwardIdx())
3200                 lyx::updateLabels(buf, it2);
3201
3202         //reset afterwards
3203         if (tabular.isLongTabular())
3204                 cnts.current_float(saveflt);
3205 }
3206
3207
3208 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3209 {
3210         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3211                              << "\n  cur:" << cur);
3212         CursorSlice sl = cur.top();
3213         Cursor & bvcur = cur.bv().cursor();
3214
3215         switch (cmd.action) {
3216
3217         case LFUN_MOUSE_PRESS:
3218                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3219
3220                 // do not reset cursor/selection if we have selected
3221                 // some cells (bug 2715).
3222                 if (cmd.button() == mouse_button::button3
3223                     && &bvcur.selBegin().inset() == this 
3224                     && tablemode(bvcur)) 
3225                         ;
3226                 else
3227                         // Let InsetText do it
3228                         cell(cur.idx())->dispatch(cur, cmd);
3229                 break;
3230         case LFUN_MOUSE_MOTION:
3231                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3232                 if (cmd.button() == mouse_button::button1) {
3233                         // only accept motions to places not deeper nested than the real anchor
3234                         if (bvcur.anchor_.hasPart(cur)) {
3235                                 // only update if selection changes
3236                                 if (bvcur.idx() == cur.idx() &&
3237                                         !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3238                                         cur.noUpdate();
3239                                 setCursorFromCoordinates(cur, cmd.x, cmd.y);
3240                                 bvcur.setCursor(cur);
3241                                 bvcur.selection() = true;
3242                         } else
3243                                 cur.undispatched();
3244                 }
3245                 break;
3246
3247         case LFUN_MOUSE_RELEASE:
3248                 //lyxerr << "# InsetTabular::MouseRelease\n" << bvcur << endl;
3249                 if (cmd.button() == mouse_button::button3)
3250                         InsetTabularMailer(*this).showDialog(&cur.bv());
3251                 break;
3252
3253         case LFUN_CELL_BACKWARD:
3254                 movePrevCell(cur);
3255                 cur.selection() = false;
3256                 break;
3257
3258         case LFUN_CELL_FORWARD:
3259                 moveNextCell(cur);
3260                 cur.selection() = false;
3261                 break;
3262
3263         case LFUN_CHAR_FORWARD_SELECT:
3264         case LFUN_CHAR_FORWARD:
3265                 cell(cur.idx())->dispatch(cur, cmd);
3266                 if (!cur.result().dispatched()) {
3267                         moveNextCell(cur);
3268                         if (sl == cur.top())
3269                                 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3270                         else
3271                                 cur.dispatched();
3272                 }
3273                 break;
3274
3275         case LFUN_CHAR_BACKWARD_SELECT:
3276         case LFUN_CHAR_BACKWARD:
3277                 cell(cur.idx())->dispatch(cur, cmd);
3278                 if (!cur.result().dispatched()) {
3279                         movePrevCell(cur);
3280                         if (sl == cur.top())
3281                                 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
3282                         else
3283                                 cur.dispatched();
3284                 }
3285                 break;
3286
3287         case LFUN_CHAR_RIGHT_SELECT:
3288         case LFUN_CHAR_RIGHT:
3289                 //FIXME: for visual cursor, really move right
3290                 if (isRightToLeft(cur))
3291                         lyx::dispatch(FuncRequest(
3292                                 cmd.action == LFUN_CHAR_RIGHT_SELECT ?
3293                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD));
3294                 else
3295                         lyx::dispatch(FuncRequest(
3296                                 cmd.action == LFUN_CHAR_RIGHT_SELECT ?
3297                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD));
3298                 break;
3299
3300         case LFUN_CHAR_LEFT_SELECT:
3301         case LFUN_CHAR_LEFT:
3302                 //FIXME: for visual cursor, really move left
3303                 if (isRightToLeft(cur))
3304                         lyx::dispatch(FuncRequest(
3305                                 cmd.action == LFUN_CHAR_LEFT_SELECT ?
3306                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD));
3307                 else
3308                         lyx::dispatch(FuncRequest(
3309                                 cmd.action == LFUN_CHAR_LEFT_SELECT ?
3310                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD));
3311                 break;
3312
3313         case LFUN_DOWN_SELECT:
3314         case LFUN_DOWN:
3315                 cell(cur.idx())->dispatch(cur, cmd);
3316                 cur.dispatched(); // override the cell's decision
3317                 if (sl == cur.top())
3318                         // if our Text didn't do anything to the cursor
3319                         // then we try to put the cursor into the cell below
3320                         // setting also the right targetX.
3321                         if (tabular.cellRow(cur.idx()) != tabular.rowCount() - 1) {
3322                                 cur.idx() = tabular.getCellBelow(cur.idx());
3323                                 cur.pit() = 0;
3324                                 TextMetrics const & tm =
3325                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3326                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3327                         }
3328                 if (sl == cur.top()) {
3329                         // we trick it to go to forward after leaving the
3330                         // tabular.
3331                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3332                         cur.undispatched();
3333                 }
3334                 break;
3335
3336         case LFUN_UP_SELECT:
3337         case LFUN_UP:
3338                 cell(cur.idx())->dispatch(cur, cmd);
3339                 cur.dispatched(); // override the cell's decision
3340                 if (sl == cur.top())
3341                         // if our Text didn't do anything to the cursor
3342                         // then we try to put the cursor into the cell above
3343                         // setting also the right targetX.
3344                         if (tabular.cellRow(cur.idx()) != 0) {
3345                                 cur.idx() = tabular.getCellAbove(cur.idx());
3346                                 cur.pit() = cur.lastpit();
3347                                 Text const * text = cell(cur.idx())->getText(0);
3348                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3349                                 ParagraphMetrics const & pm =
3350                                         tm.parMetrics(cur.lastpit());
3351                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3352                         }
3353                 if (sl == cur.top()) {
3354                         cmd = FuncRequest(LFUN_UP);
3355                         cur.undispatched();
3356                 }
3357                 break;
3358
3359 //      case LFUN_SCREEN_DOWN: {
3360 //              //if (hasSelection())
3361 //              //      cur.selection() = false;
3362 //              col_type const col = tabular.cellColumn(cur.idx());
3363 //              int const t =   cur.bv().top_y() + cur.bv().height();
3364 //              if (t < yo() + tabular.getHeightOfTabular()) {
3365 //                      cur.bv().scrollDocView(t);
3366 //                      cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
3367 //              } else {
3368 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3369 //              }
3370 //              cur.par() = 0;
3371 //              cur.pos() = 0;
3372 //              break;
3373 //      }
3374 //
3375 //      case LFUN_SCREEN_UP: {
3376 //              //if (hasSelection())
3377 //              //      cur.selection() = false;
3378 //              col_type const col = tabular.cellColumn(cur.idx());
3379 //              int const t =   cur.bv().top_y() + cur.bv().height();
3380 //              if (yo() < 0) {
3381 //                      cur.bv().scrollDocView(t);
3382 //                      if (yo() > 0)
3383 //                              cur.idx() = col;
3384 //                      else
3385 //                              cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
3386 //              } else {
3387 //                      cur.idx() = col;
3388 //              }
3389 //              cur.par() = cur.lastpar();
3390 //              cur.pos() = cur.lastpos();
3391 //              break;
3392 //      }
3393
3394         case LFUN_LAYOUT_TABULAR:
3395                 InsetTabularMailer(*this).showDialog(&cur.bv());
3396                 break;
3397
3398         case LFUN_INSET_DIALOG_UPDATE:
3399                 InsetTabularMailer(*this).updateDialog(&cur.bv());
3400                 break;
3401
3402         case LFUN_TABULAR_FEATURE:
3403                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3404                         cur.undispatched();
3405                 break;
3406
3407         // insert file functions
3408         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3409         case LFUN_FILE_INSERT_PLAINTEXT: {
3410                 // FIXME UNICODE
3411                 docstring const tmpstr = cur.bv().contentsOfPlaintextFile(to_utf8(cmd.argument()), false);
3412                 if (!tmpstr.empty() && !insertPlaintextString(cur.bv(), tmpstr, false))
3413                         cur.undispatched();
3414                 break;
3415         }
3416
3417         case LFUN_CUT:
3418                 if (tablemode(cur)) {
3419                         if (copySelection(cur)) {
3420                                 cur.recordUndoInset(DELETE_UNDO);
3421                                 cutSelection(cur);
3422                         }
3423                 }
3424                 else
3425                         cell(cur.idx())->dispatch(cur, cmd);
3426                 break;
3427
3428         case LFUN_CHAR_DELETE_BACKWARD:
3429         case LFUN_CHAR_DELETE_FORWARD:
3430                 if (tablemode(cur)) {
3431                         cur.recordUndoInset(DELETE_UNDO);
3432                         cutSelection(cur);
3433                 }
3434                 else
3435                         cell(cur.idx())->dispatch(cur, cmd);
3436                 break;
3437
3438         case LFUN_COPY:
3439                 if (!cur.selection())
3440                         break;
3441                 if (tablemode(cur)) {
3442                         cur.finishUndo();
3443                         copySelection(cur);
3444                 } else
3445                         cell(cur.idx())->dispatch(cur, cmd);
3446                 break;
3447
3448         case LFUN_CLIPBOARD_PASTE:
3449         case LFUN_PRIMARY_SELECTION_PASTE: {
3450                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3451                         theClipboard().getAsText() :
3452                         theSelection().get();
3453                 if (clip.empty())
3454                         break;
3455                 // pass to InsertPlaintextString, but
3456                 // only if we have multi-cell content
3457                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3458                         if (insertPlaintextString(cur.bv(), clip, false)) {
3459                                 // content has been replaced,
3460                                 // so cursor might be invalid
3461                                 cur.pos() = cur.lastpos();
3462                                 bvcur.setCursor(cur);
3463                                 break;
3464                         }
3465                 }
3466                 // Let the cell handle normal text
3467                 cell(cur.idx())->dispatch(cur, cmd);
3468                 break;
3469         }
3470
3471         case LFUN_PASTE:
3472                 if (tabularStackDirty() && theClipboard().isInternal()) {
3473                         cur.recordUndoInset(INSERT_UNDO);
3474                         pasteClipboard(cur);
3475                         break;
3476                 }
3477                 cell(cur.idx())->dispatch(cur, cmd);
3478                 break;
3479
3480         case LFUN_FONT_EMPH:
3481         case LFUN_FONT_BOLD:
3482         case LFUN_FONT_ROMAN:
3483         case LFUN_FONT_NOUN:
3484         case LFUN_FONT_ITAL:
3485         case LFUN_FONT_FRAK:
3486         case LFUN_FONT_TYPEWRITER:
3487         case LFUN_FONT_SANS:
3488         case LFUN_FONT_FREE_APPLY:
3489         case LFUN_FONT_FREE_UPDATE:
3490         case LFUN_FONT_SIZE:
3491         case LFUN_FONT_UNDERLINE:
3492         case LFUN_LANGUAGE:
3493         case LFUN_WORD_CAPITALIZE:
3494         case LFUN_WORD_UPCASE:
3495         case LFUN_WORD_LOWCASE:
3496         case LFUN_CHARS_TRANSPOSE:
3497                 if (tablemode(cur)) {
3498                         row_type rs, re;
3499                         col_type cs, ce;
3500                         getSelection(cur, rs, re, cs, ce);
3501                         Cursor tmpcur = cur;
3502                         for (row_type i = rs; i <= re; ++i) {
3503                                 for (col_type j = cs; j <= ce; ++j) {
3504                                         // cursor follows cell:
3505                                         tmpcur.idx() = tabular.cellIndex(i, j);
3506                                         // select this cell only:
3507                                         tmpcur.pit() = 0;
3508                                         tmpcur.pos() = 0;
3509                                         tmpcur.resetAnchor();
3510                                         tmpcur.pit() = tmpcur.lastpit();
3511                                         tmpcur.pos() = tmpcur.top().lastpos();
3512                                         tmpcur.setCursor(tmpcur);
3513                                         tmpcur.setSelection();
3514                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3515                                 }
3516                         }
3517                         break;
3518                 } else {
3519                         cell(cur.idx())->dispatch(cur, cmd);
3520                         break;
3521                 }
3522         default:
3523                 // we try to handle this event in the insets dispatch function.
3524                 cell(cur.idx())->dispatch(cur, cmd);
3525                 break;
3526         }
3527 }
3528
3529
3530 // function sets an object as defined in func_status.h:
3531 // states OK, Unknown, Disabled, On, Off.
3532 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3533         FuncStatus & status) const
3534 {
3535         switch (cmd.action) {
3536         case LFUN_TABULAR_FEATURE: {
3537                 int action = Tabular::LAST_ACTION;
3538                 int i = 0;
3539                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3540                         string const tmp = tabularFeature[i].feature;
3541                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3542                                 action = tabularFeature[i].action;
3543                                 break;
3544                         }
3545                 }
3546                 if (action == Tabular::LAST_ACTION) {
3547                         status.clear();
3548                         status.unknown(true);
3549                         return true;
3550                 }
3551
3552                 string const argument
3553                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3554
3555                 row_type sel_row_start = 0;
3556                 row_type sel_row_end = 0;
3557                 col_type sel_col_start = 0;
3558                 col_type sel_col_end = 0;
3559                 Tabular::ltType dummyltt;
3560                 bool flag = true;
3561
3562                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3563
3564                 switch (action) {
3565                 case Tabular::SET_PWIDTH:
3566                 case Tabular::SET_MPWIDTH:
3567                 case Tabular::SET_SPECIAL_COLUMN:
3568                 case Tabular::SET_SPECIAL_MULTI:
3569                 case Tabular::APPEND_ROW:
3570                 case Tabular::APPEND_COLUMN:
3571                 case Tabular::DELETE_ROW:
3572                 case Tabular::DELETE_COLUMN:
3573                 case Tabular::COPY_ROW:
3574                 case Tabular::COPY_COLUMN:
3575                 case Tabular::SET_ALL_LINES:
3576                 case Tabular::UNSET_ALL_LINES:
3577                 case Tabular::SET_TOP_SPACE:
3578                 case Tabular::SET_BOTTOM_SPACE:
3579                 case Tabular::SET_INTERLINE_SPACE:
3580                         status.clear();
3581                         return true;
3582
3583                 case Tabular::MULTICOLUMN:
3584                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3585                         break;
3586
3587                 case Tabular::M_TOGGLE_LINE_TOP:
3588                         flag = false;
3589                 case Tabular::TOGGLE_LINE_TOP:
3590                         status.setOnOff(tabular.topLine(cur.idx(), flag));
3591                         break;
3592
3593                 case Tabular::M_TOGGLE_LINE_BOTTOM:
3594                         flag = false;
3595                 case Tabular::TOGGLE_LINE_BOTTOM:
3596                         status.setOnOff(tabular.bottomLine(cur.idx(), flag));
3597                         break;
3598
3599                 case Tabular::M_TOGGLE_LINE_LEFT:
3600                         flag = false;
3601                 case Tabular::TOGGLE_LINE_LEFT:
3602                         status.setOnOff(tabular.leftLine(cur.idx(), flag));
3603                         break;
3604
3605                 case Tabular::M_TOGGLE_LINE_RIGHT:
3606                         flag = false;
3607                 case Tabular::TOGGLE_LINE_RIGHT:
3608                         status.setOnOff(tabular.rightLine(cur.idx(), flag));
3609                         break;
3610
3611                 case Tabular::M_ALIGN_LEFT:
3612                         flag = false;
3613                 case Tabular::ALIGN_LEFT:
3614                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3615                         break;
3616
3617                 case Tabular::M_ALIGN_RIGHT:
3618                         flag = false;
3619                 case Tabular::ALIGN_RIGHT:
3620                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3621                         break;
3622
3623                 case Tabular::M_ALIGN_CENTER:
3624                         flag = false;
3625                 case Tabular::ALIGN_CENTER:
3626                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3627                         break;
3628
3629                 case Tabular::ALIGN_BLOCK:
3630                         status.enabled(!tabular.getPWidth(cur.idx()).zero());
3631                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3632                         break;
3633
3634                 case Tabular::M_VALIGN_TOP:
3635                         flag = false;
3636                 case Tabular::VALIGN_TOP:
3637                         status.setOnOff(
3638                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3639                         break;
3640
3641                 case Tabular::M_VALIGN_BOTTOM:
3642                         flag = false;
3643                 case Tabular::VALIGN_BOTTOM:
3644                         status.setOnOff(
3645                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3646                         break;
3647
3648                 case Tabular::M_VALIGN_MIDDLE:
3649                         flag = false;
3650                 case Tabular::VALIGN_MIDDLE:
3651                         status.setOnOff(
3652                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3653                         break;
3654
3655                 case Tabular::SET_LONGTABULAR:
3656                         status.setOnOff(tabular.isLongTabular());
3657                         break;
3658
3659                 case Tabular::UNSET_LONGTABULAR:
3660                         status.setOnOff(!tabular.isLongTabular());
3661                         break;
3662
3663                 case Tabular::TOGGLE_ROTATE_TABULAR:
3664                 case Tabular::SET_ROTATE_TABULAR:
3665                         status.setOnOff(tabular.getRotateTabular());
3666                         break;
3667
3668                 case Tabular::UNSET_ROTATE_TABULAR:
3669                         status.setOnOff(!tabular.getRotateTabular());
3670                         break;
3671
3672                 case Tabular::TOGGLE_ROTATE_CELL:
3673                 case Tabular::SET_ROTATE_CELL:
3674                         status.setOnOff(!oneCellHasRotationState(false,
3675                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3676                         break;
3677
3678                 case Tabular::UNSET_ROTATE_CELL:
3679                         status.setOnOff(!oneCellHasRotationState(true,
3680                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3681                         break;
3682
3683                 case Tabular::SET_USEBOX:
3684                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
3685                         break;
3686
3687                 case Tabular::SET_LTFIRSTHEAD:
3688                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3689                         break;
3690
3691                 case Tabular::UNSET_LTFIRSTHEAD:
3692                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3693                         break;
3694
3695                 case Tabular::SET_LTHEAD:
3696                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3697                         break;
3698
3699                 case Tabular::UNSET_LTHEAD:
3700                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3701                         break;
3702
3703                 case Tabular::SET_LTFOOT:
3704                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3705                         break;
3706
3707                 case Tabular::UNSET_LTFOOT:
3708                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3709                         break;
3710
3711                 case Tabular::SET_LTLASTFOOT:
3712                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3713                         break;
3714
3715                 case Tabular::UNSET_LTLASTFOOT:
3716                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3717                         break;
3718
3719                 case Tabular::SET_LTNEWPAGE:
3720                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
3721                         break;
3722
3723                 case Tabular::SET_BOOKTABS:
3724                         status.setOnOff(tabular.useBookTabs());
3725                         break;
3726
3727                 case Tabular::UNSET_BOOKTABS:
3728                         status.setOnOff(!tabular.useBookTabs());
3729                         break;
3730
3731                 default:
3732                         status.clear();
3733                         status.enabled(false);
3734                         break;
3735                 }
3736                 return true;
3737         }
3738
3739         // These are only enabled inside tabular
3740         case LFUN_CELL_BACKWARD:
3741         case LFUN_CELL_FORWARD:
3742                 status.enabled(true);
3743                 return true;
3744
3745         // disable these with multiple cells selected
3746         case LFUN_INSET_INSERT:
3747         case LFUN_TABULAR_INSERT:
3748         case LFUN_FLEX_INSERT:
3749         case LFUN_FLOAT_INSERT:
3750         case LFUN_FLOAT_WIDE_INSERT:
3751         case LFUN_FOOTNOTE_INSERT:
3752         case LFUN_MARGINALNOTE_INSERT:
3753         case LFUN_MATH_INSERT:
3754         case LFUN_MATH_MODE:
3755         case LFUN_MATH_MUTATE:
3756         case LFUN_MATH_DISPLAY:
3757         case LFUN_NOTE_INSERT:
3758         case LFUN_OPTIONAL_INSERT:
3759         case LFUN_BOX_INSERT:
3760         case LFUN_BRANCH_INSERT:
3761         case LFUN_WRAP_INSERT:
3762         case LFUN_ERT_INSERT: {
3763                 if (tablemode(cur)) {
3764                         status.enabled(false);
3765                         return true;
3766                 } else
3767                         return cell(cur.idx())->getStatus(cur, cmd, status);
3768         }
3769
3770         // disable in non-fixed-width cells
3771         case LFUN_BREAK_LINE:
3772         case LFUN_BREAK_PARAGRAPH:
3773         case LFUN_BREAK_PARAGRAPH_SKIP: {
3774                 if (tabular.getPWidth(cur.idx()).zero()) {
3775                         status.enabled(false);
3776                         return true;
3777                 } else
3778                         return cell(cur.idx())->getStatus(cur, cmd, status);
3779         }
3780
3781         case LFUN_PASTE:
3782                 if (tabularStackDirty() && theClipboard().isInternal()) {
3783                         status.enabled(true);
3784                         return true;
3785                 } else
3786                         return cell(cur.idx())->getStatus(cur, cmd, status);
3787
3788         case LFUN_INSET_MODIFY:
3789                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
3790                         status.enabled(true);
3791                         return true;
3792                 }
3793                 // Fall through
3794
3795         default:
3796                 // we try to handle this event in the insets dispatch function.
3797                 return cell(cur.idx())->getStatus(cur, cmd, status);
3798         }
3799 }
3800
3801
3802 int InsetTabular::latex(Buffer const & buf, odocstream & os,
3803                         OutputParams const & runparams) const
3804 {
3805         return tabular.latex(buf, os, runparams);
3806 }
3807
3808
3809 int InsetTabular::plaintext(Buffer const & buf, odocstream & os,
3810                             OutputParams const & runparams) const
3811 {
3812         os << '\n'; // output table on a new line
3813         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
3814         tabular.plaintext(buf, os, runparams, dp, false, 0);
3815         return PLAINTEXT_NEWLINE;
3816 }
3817
3818
3819 int InsetTabular::docbook(Buffer const & buf, odocstream & os,
3820                           OutputParams const & runparams) const
3821 {
3822         int ret = 0;
3823         Inset * master = 0;
3824
3825         // FIXME: Why not pass a proper DocIterator here?
3826 #if 0
3827         // if the table is inside a float it doesn't need the informaltable
3828         // wrapper. Search for it.
3829         for (master = owner(); master; master = master->owner())
3830                 if (master->lyxCode() == FLOAT_CODE)
3831                         break;
3832 #endif
3833
3834         if (!master) {
3835                 os << "<informaltable>";
3836                 ++ret;
3837         }
3838         ret += tabular.docbook(buf, os, runparams);
3839         if (!master) {
3840                 os << "</informaltable>";
3841                 ++ret;
3842         }
3843         return ret;
3844 }
3845
3846
3847 void InsetTabular::validate(LaTeXFeatures & features) const
3848 {
3849         tabular.validate(features);
3850 }
3851
3852
3853 shared_ptr<InsetText const> InsetTabular::cell(idx_type idx) const
3854 {
3855         return tabular.getCellInset(idx);
3856 }
3857
3858
3859 shared_ptr<InsetText> InsetTabular::cell(idx_type idx)
3860 {
3861         return tabular.getCellInset(idx);
3862 }
3863
3864
3865 void InsetTabular::cursorPos(BufferView const & bv,
3866                 CursorSlice const & sl, bool boundary, int & x, int & y) const
3867 {
3868         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
3869
3870         // y offset     correction
3871         int const row = tabular.cellRow(sl.idx());
3872         for (int i = 0; i <= row; ++i) {
3873                 if (i != 0) {
3874                         y += tabular.rowAscent(i);
3875                         y += tabular.getAdditionalHeight(i);
3876                 }
3877                 if (i != row)
3878                         y += tabular.rowDescent(i);
3879         }
3880
3881         // x offset correction
3882         int const col = tabular.cellColumn(sl.idx());
3883         int idx = tabular.cellIndex(row, 0);
3884         for (int j = 0; j < col; ++j) {
3885                 if (tabular.isPartOfMultiColumn(row, j))
3886                         continue;
3887                 x += tabular.columnWidth(idx);
3888                 ++idx;
3889         }
3890         x += tabular.getBeginningOfTextInCell(idx);
3891         x += ADD_TO_TABULAR_WIDTH;
3892         x += scx_;
3893 }
3894
3895
3896 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
3897 {
3898         int xx = 0;
3899         int yy = 0;
3900         Inset const & inset = *tabular.getCellInset(cell);
3901         Point o = bv.coordCache().getInsets().xy(&inset);
3902         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
3903         int const xend = xbeg + tabular.columnWidth(cell);
3904         row_type const row = tabular.cellRow(cell);
3905         int const ybeg = o.y_ - tabular.rowAscent(row) -
3906                          tabular.getAdditionalHeight(row);
3907         int const yend = o.y_ + tabular.rowDescent(row);
3908
3909         if (x < xbeg)
3910                 xx = xbeg - x;
3911         else if (x > xend)
3912                 xx = x - xend;
3913
3914         if (y < ybeg)
3915                 yy = ybeg - y;
3916         else if (y > yend)
3917                 yy = y - yend;
3918
3919         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
3920         //       << " ybeg=" << ybeg << " yend=" << yend
3921         //       << " xx=" << xx << " yy=" << yy
3922         //       << " dist=" << xx + yy << endl;
3923         return xx + yy;
3924 }
3925
3926
3927 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
3928 {
3929         //lyxerr << "InsetTabular::editXY: " << this << endl;
3930         cur.selection() = false;
3931         cur.push(*this);
3932         cur.idx() = getNearestCell(cur.bv(), x, y);
3933         resetPos(cur);
3934         return cur.bv().textMetrics(&cell(cur.idx())->text_).editXY(cur, x, y);
3935 }
3936
3937
3938 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
3939 {
3940         cur.idx() = getNearestCell(cur.bv(), x, y);
3941         cur.bv().textMetrics(&cell(cur.idx())->text_).setCursorFromCoordinates(cur, x, y);
3942 }
3943
3944
3945 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
3946 {
3947         idx_type idx_min = 0;
3948         int dist_min = std::numeric_limits<int>::max();
3949         for (idx_type i = 0, n = nargs(); i != n; ++i) {
3950                 if (bv.coordCache().getInsets().has(tabular.getCellInset(i).get())) {
3951                         int const d = dist(bv, i, x, y);
3952                         if (d < dist_min) {
3953                                 dist_min = d;
3954                                 idx_min = i;
3955                         }
3956                 }
3957         }
3958         return idx_min;
3959 }
3960
3961
3962 int InsetTabular::getCellXPos(idx_type const cell) const
3963 {
3964         idx_type c = cell;
3965
3966         for (; !tabular.isFirstCellInRow(c); --c)
3967                 ;
3968         int lx = 0;
3969         for (; c < cell; ++c)
3970                 lx += tabular.columnWidth(c);
3971
3972         return lx;
3973 }
3974
3975
3976 void InsetTabular::resetPos(Cursor & cur) const
3977 {
3978         BufferView & bv = cur.bv();
3979         int const maxwidth = bv.workWidth();
3980
3981         if (&cur.inset() != this) {
3982                 scx_ = 0;
3983         } else {
3984                 int const X1 = 0;
3985                 int const X2 = maxwidth;
3986                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
3987                 int const x1 = xo(cur.bv()) + getCellXPos(cur.idx()) + offset;
3988                 int const x2 = x1 + tabular.columnWidth(cur.idx());
3989
3990                 if (x1 < X1)
3991                         scx_ = X1 + 20 - x1;
3992                 else if (x2 > X2)
3993                         scx_ = X2 - 20 - x2;
3994                 else
3995                         scx_ = 0;
3996         }
3997
3998         cur.updateFlags(Update::Force | Update::FitCursor);
3999 }
4000
4001
4002 void InsetTabular::moveNextCell(Cursor & cur)
4003 {
4004         if (isRightToLeft(cur)) {
4005                 if (tabular.isFirstCellInRow(cur.idx())) {
4006                         row_type const row = tabular.cellRow(cur.idx());
4007                         if (row == tabular.rowCount() - 1)
4008                                 return;
4009                         cur.idx() = tabular.getCellBelow(tabular.getLastCellInRow(row));
4010                 } else {
4011                         if (cur.idx() == 0)
4012                                 return;
4013                         --cur.idx();
4014                 }
4015         } else {
4016                 if (tabular.isLastCell(cur.idx()))
4017                         return;
4018                 ++cur.idx();
4019         }
4020         cur.pit() = 0;
4021         cur.pos() = 0;
4022         resetPos(cur);
4023 }
4024
4025
4026 void InsetTabular::movePrevCell(Cursor & cur)
4027 {
4028         if (isRightToLeft(cur)) {
4029                 if (tabular.isLastCellInRow(cur.idx())) {
4030                         row_type const row = tabular.cellRow(cur.idx());
4031                         if (row == 0)
4032                                 return;
4033                         cur.idx() = tabular.getFirstCellInRow(row);
4034                         cur.idx() = tabular.getCellAbove(cur.idx());
4035                 } else {
4036                         if (tabular.isLastCell(cur.idx()))
4037                                 return;
4038                         ++cur.idx();
4039                 }
4040         } else {
4041                 if (cur.idx() == 0) // first cell
4042                         return;
4043                 --cur.idx();
4044         }
4045         cur.pit() = cur.lastpit();
4046         cur.pos() = cur.lastpos();
4047
4048         // FIXME: this accesses the position cache before it is initialized
4049         //resetPos(cur);
4050 }
4051
4052
4053 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4054 {
4055         Tabular::Feature action = Tabular::LAST_ACTION;
4056
4057         int i = 0;
4058         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4059                 string const tmp = tabularFeature[i].feature;
4060
4061                 if (tmp == what.substr(0, tmp.length())) {
4062                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4063                         //tabularFeatures[i].feature.length()))
4064                         action = tabularFeature[i].action;
4065                         break;
4066                 }
4067         }
4068         if (action == Tabular::LAST_ACTION)
4069                 return false;
4070
4071         string const val =
4072                 ltrim(what.substr(tabularFeature[i].feature.length()));
4073         tabularFeatures(cur, action, val);
4074         return true;
4075 }
4076
4077
4078 static void checkLongtableSpecial(Tabular::ltType & ltt,
4079                           string const & special, bool & flag)
4080 {
4081         if (special == "dl_above") {
4082                 ltt.topDL = flag;
4083                 ltt.set = false;
4084         } else if (special == "dl_below") {
4085                 ltt.bottomDL = flag;
4086                 ltt.set = false;
4087         } else if (special == "empty") {
4088                 ltt.empty = flag;
4089                 ltt.set = false;
4090         } else if (flag) {
4091                 ltt.empty = false;
4092                 ltt.set = true;
4093         }
4094 }
4095
4096 bool InsetTabular::oneCellHasRotationState(bool rotated,
4097                 row_type row_start, row_type row_end,
4098                 col_type col_start, col_type col_end) const {
4099
4100         for (row_type i = row_start; i <= row_end; ++i) {
4101                 for (col_type j = col_start; j <= col_end; ++j) {
4102                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4103                                 == rotated) {
4104                                 return true;
4105                         }
4106                 }
4107         }
4108         return false;
4109 }
4110
4111 void InsetTabular::tabularFeatures(Cursor & cur,
4112         Tabular::Feature feature, string const & value)
4113 {
4114         BufferView & bv = cur.bv();
4115         col_type sel_col_start;
4116         col_type sel_col_end;
4117         row_type sel_row_start;
4118         row_type sel_row_end;
4119         bool setLines = false;
4120         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4121         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4122
4123         switch (feature) {
4124
4125         case Tabular::M_ALIGN_LEFT:
4126         case Tabular::ALIGN_LEFT:
4127                 setAlign = LYX_ALIGN_LEFT;
4128                 break;
4129
4130         case Tabular::M_ALIGN_RIGHT:
4131         case Tabular::ALIGN_RIGHT:
4132                 setAlign = LYX_ALIGN_RIGHT;
4133                 break;
4134
4135         case Tabular::M_ALIGN_CENTER:
4136         case Tabular::ALIGN_CENTER:
4137                 setAlign = LYX_ALIGN_CENTER;
4138                 break;
4139
4140         case Tabular::ALIGN_BLOCK:
4141                 setAlign = LYX_ALIGN_BLOCK;
4142                 break;
4143
4144         case Tabular::M_VALIGN_TOP:
4145         case Tabular::VALIGN_TOP:
4146                 setVAlign = Tabular::LYX_VALIGN_TOP;
4147                 break;
4148
4149         case Tabular::M_VALIGN_BOTTOM:
4150         case Tabular::VALIGN_BOTTOM:
4151                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4152                 break;
4153
4154         case Tabular::M_VALIGN_MIDDLE:
4155         case Tabular::VALIGN_MIDDLE:
4156                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4157                 break;
4158
4159         default:
4160                 break;
4161         }
4162
4163         cur.recordUndoInset(ATOMIC_UNDO);
4164
4165         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4166         row_type const row = tabular.cellRow(cur.idx());
4167         col_type const column = tabular.cellColumn(cur.idx());
4168         bool flag = true;
4169         Tabular::ltType ltt;
4170
4171         switch (feature) {
4172
4173         case Tabular::SET_PWIDTH: {
4174                 Length const len(value);
4175                 tabular.setColumnPWidth(cur, cur.idx(), len);
4176                 if (len.zero()
4177                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4178                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4179                 break;
4180         }
4181
4182         case Tabular::SET_MPWIDTH:
4183                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4184                 break;
4185
4186         case Tabular::SET_SPECIAL_COLUMN:
4187         case Tabular::SET_SPECIAL_MULTI:
4188                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4189                 break;
4190
4191         case Tabular::APPEND_ROW:
4192                 // append the row into the tabular
4193                 tabular.appendRow(bv.buffer().params(), cur.idx());
4194                 break;
4195
4196         case Tabular::APPEND_COLUMN:
4197                 // append the column into the tabular
4198                 tabular.appendColumn(bv.buffer().params(), cur.idx());
4199                 cur.idx() = tabular.cellIndex(row, column);
4200                 break;
4201
4202         case Tabular::DELETE_ROW:
4203                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4204                         tabular.deleteRow(sel_row_start);
4205                 if (sel_row_start >= tabular.rowCount())
4206                         --sel_row_start;
4207                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4208                 cur.pit() = 0;
4209                 cur.pos() = 0;
4210                 cur.selection() = false;
4211                 break;
4212
4213         case Tabular::DELETE_COLUMN:
4214                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4215                         tabular.deleteColumn(sel_col_start);
4216                 if (sel_col_start >= tabular.columnCount())
4217                         --sel_col_start;
4218                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4219                 cur.pit() = 0;
4220                 cur.pos() = 0;
4221                 cur.selection() = false;
4222                 break;
4223
4224         case Tabular::COPY_ROW:
4225                 tabular.copyRow(bv.buffer().params(), row);
4226                 break;
4227
4228         case Tabular::COPY_COLUMN:
4229                 tabular.copyColumn(bv.buffer().params(), column);
4230                 cur.idx() = tabular.cellIndex(row, column);
4231                 break;
4232
4233         case Tabular::M_TOGGLE_LINE_TOP:
4234                 flag = false;
4235         case Tabular::TOGGLE_LINE_TOP: {
4236                 bool lineSet = !tabular.topLine(cur.idx(), flag);
4237                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4238                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4239                                 tabular.setTopLine(
4240                                         tabular.cellIndex(i, j),
4241                                         lineSet, flag);
4242                 break;
4243         }
4244
4245         case Tabular::M_TOGGLE_LINE_BOTTOM:
4246                 flag = false;
4247         case Tabular::TOGGLE_LINE_BOTTOM: {
4248                 bool lineSet = !tabular.bottomLine(cur.idx(), flag);
4249                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4250                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4251                                 tabular.setBottomLine(
4252                                         tabular.cellIndex(i, j),
4253                                         lineSet,
4254                                         flag);
4255                 break;
4256         }
4257
4258         case Tabular::M_TOGGLE_LINE_LEFT:
4259                 flag = false;
4260         case Tabular::TOGGLE_LINE_LEFT: {
4261                 bool lineSet = !tabular.leftLine(cur.idx(), flag);
4262                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4263                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4264                                 tabular.setLeftLine(
4265                                         tabular.cellIndex(i,j),
4266                                         lineSet,
4267                                         flag);
4268                 break;
4269         }
4270
4271         case Tabular::M_TOGGLE_LINE_RIGHT:
4272                 flag = false;
4273         case Tabular::TOGGLE_LINE_RIGHT: {
4274                 bool lineSet = !tabular.rightLine(cur.idx(), flag);
4275                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4276                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4277                                 tabular.setRightLine(
4278                                         tabular.cellIndex(i,j),
4279                                         lineSet,
4280                                         flag);
4281                 break;
4282         }
4283
4284         case Tabular::M_ALIGN_LEFT:
4285         case Tabular::M_ALIGN_RIGHT:
4286         case Tabular::M_ALIGN_CENTER:
4287                 flag = false;
4288         case Tabular::ALIGN_LEFT:
4289         case Tabular::ALIGN_RIGHT:
4290         case Tabular::ALIGN_CENTER:
4291         case Tabular::ALIGN_BLOCK:
4292                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4293                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4294                                 tabular.setAlignment(
4295                                         tabular.cellIndex(i, j),
4296                                         setAlign,
4297                                         flag);
4298                 break;
4299
4300         case Tabular::M_VALIGN_TOP:
4301         case Tabular::M_VALIGN_BOTTOM:
4302         case Tabular::M_VALIGN_MIDDLE:
4303                 flag = false;
4304         case Tabular::VALIGN_TOP:
4305         case Tabular::VALIGN_BOTTOM:
4306         case Tabular::VALIGN_MIDDLE:
4307                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4308                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4309                                 tabular.setVAlignment(
4310                                         tabular.cellIndex(i, j),
4311                                         setVAlign, flag);
4312                 break;
4313
4314         case Tabular::MULTICOLUMN: {
4315                 if (sel_row_start != sel_row_end) {
4316                         // FIXME: Need I say it ? This is horrible.
4317                         // FIXME UNICODE
4318                         Alert::error(_("Error setting multicolumn"),
4319                                      _("You cannot set multicolumn vertically."));
4320                         return;
4321                 }
4322                 if (!cur.selection()) {
4323                         // just multicol for one single cell
4324                         // check whether we are completely in a multicol
4325                         if (tabular.isMultiColumn(cur.idx()))
4326                                 tabular.unsetMultiColumn(cur.idx());
4327                         else
4328                                 tabular.setMultiColumn(&bv.buffer(), cur.idx(), 1);
4329                         break;
4330                 }
4331                 // we have a selection so this means we just add all this
4332                 // cells to form a multicolumn cell
4333                 idx_type const s_start = cur.selBegin().idx();
4334                 idx_type const s_end = cur.selEnd().idx();
4335                 tabular.setMultiColumn(&bv.buffer(), s_start, s_end - s_start + 1);
4336                 cur.idx() = s_start;
4337                 cur.pit() = 0;
4338                 cur.pos() = 0;
4339                 cur.selection() = false;
4340                 break;
4341         }
4342
4343         case Tabular::SET_ALL_LINES:
4344                 setLines = true;
4345         case Tabular::UNSET_ALL_LINES:
4346                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4347                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4348                                 tabular.setAllLines(
4349                                         tabular.cellIndex(i,j), setLines);
4350                 break;
4351
4352         case Tabular::SET_LONGTABULAR:
4353                 tabular.setLongTabular(true);
4354                 break;
4355
4356         case Tabular::UNSET_LONGTABULAR:
4357                 tabular.setLongTabular(false);
4358                 break;
4359
4360         case Tabular::SET_ROTATE_TABULAR:
4361                 tabular.setRotateTabular(true);
4362                 break;
4363
4364         case Tabular::UNSET_ROTATE_TABULAR:
4365                 tabular.setRotateTabular(false);
4366                 break;
4367
4368         case Tabular::TOGGLE_ROTATE_TABULAR:
4369                 tabular.setRotateTabular(!tabular.getRotateTabular());
4370                 break;
4371
4372         case Tabular::SET_ROTATE_CELL:
4373                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4374                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4375                                 tabular.setRotateCell(
4376                                         tabular.cellIndex(i, j), true);
4377                 break;
4378
4379         case Tabular::UNSET_ROTATE_CELL:
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.setRotateCell(
4383                                         tabular.cellIndex(i, j), false);
4384                 break;
4385
4386         case Tabular::TOGGLE_ROTATE_CELL:
4387                 {
4388                 bool oneNotRotated = oneCellHasRotationState(false,
4389                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4390
4391                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4392                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4393                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4394                                                                           oneNotRotated);
4395                 }
4396                 break;
4397
4398         case Tabular::SET_USEBOX: {
4399                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4400                 if (val == tabular.getUsebox(cur.idx()))
4401                         val = Tabular::BOX_NONE;
4402                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4403                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4404                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4405                 break;
4406         }
4407
4408         case Tabular::UNSET_LTFIRSTHEAD:
4409                 flag = false;
4410         case Tabular::SET_LTFIRSTHEAD:
4411                 tabular.getRowOfLTFirstHead(row, ltt);
4412                 checkLongtableSpecial(ltt, value, flag);
4413                 tabular.setLTHead(row, flag, ltt, true);
4414                 break;
4415
4416         case Tabular::UNSET_LTHEAD:
4417                 flag = false;
4418         case Tabular::SET_LTHEAD:
4419                 tabular.getRowOfLTHead(row, ltt);
4420                 checkLongtableSpecial(ltt, value, flag);
4421                 tabular.setLTHead(row, flag, ltt, false);
4422                 break;
4423
4424         case Tabular::UNSET_LTFOOT:
4425                 flag = false;
4426         case Tabular::SET_LTFOOT:
4427                 tabular.getRowOfLTFoot(row, ltt);
4428                 checkLongtableSpecial(ltt, value, flag);
4429                 tabular.setLTFoot(row, flag, ltt, false);
4430                 break;
4431
4432         case Tabular::UNSET_LTLASTFOOT:
4433                 flag = false;
4434         case Tabular::SET_LTLASTFOOT:
4435                 tabular.getRowOfLTLastFoot(row, ltt);
4436                 checkLongtableSpecial(ltt, value, flag);
4437                 tabular.setLTFoot(row, flag, ltt, true);
4438                 break;
4439
4440         case Tabular::SET_LTNEWPAGE:
4441                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4442                 break;
4443
4444         case Tabular::SET_BOOKTABS:
4445                 tabular.setBookTabs(true);
4446                 break;
4447
4448         case Tabular::UNSET_BOOKTABS:
4449                 tabular.setBookTabs(false);
4450                 break;
4451
4452         case Tabular::SET_TOP_SPACE: {
4453                 Length len;
4454                 if (value == "default")
4455                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4456                                 tabular.row_info[i].top_space_default = true;
4457                 else if (isValidLength(value, &len))
4458                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4459                                 tabular.row_info[i].top_space_default = false;
4460                                 tabular.row_info[i].top_space = len;
4461                         }
4462                 else
4463                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4464                                 tabular.row_info[i].top_space_default = false;
4465                                 tabular.row_info[i].top_space = len;
4466                         }
4467                 break;
4468         }
4469
4470         case Tabular::SET_BOTTOM_SPACE: {
4471                 Length len;
4472                 if (value == "default")
4473                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4474                                 tabular.row_info[i].bottom_space_default = true;
4475                 else if (isValidLength(value, &len))
4476                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4477                                 tabular.row_info[i].bottom_space_default = false;
4478                                 tabular.row_info[i].bottom_space = len;
4479                         }
4480                 else
4481                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4482                                 tabular.row_info[i].bottom_space_default = false;
4483                                 tabular.row_info[i].bottom_space = len;
4484                         }
4485                 break;
4486         }
4487
4488         case Tabular::SET_INTERLINE_SPACE: {
4489                 Length len;
4490                 if (value == "default")
4491                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4492                                 tabular.row_info[i].interline_space_default = true;
4493                 else if (isValidLength(value, &len))
4494                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4495                                 tabular.row_info[i].interline_space_default = false;
4496                                 tabular.row_info[i].interline_space = len;
4497                         }
4498                 else
4499                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4500                                 tabular.row_info[i].interline_space_default = false;
4501                                 tabular.row_info[i].interline_space = len;
4502                         }
4503                 break;
4504         }
4505
4506         // dummy stuff just to avoid warnings
4507         case Tabular::LAST_ACTION:
4508                 break;
4509         }
4510 }
4511
4512
4513 bool InsetTabular::showInsetDialog(BufferView * bv) const
4514 {
4515         InsetTabularMailer(*this).showDialog(bv);
4516         return true;
4517 }
4518
4519
4520 void InsetTabular::openLayoutDialog(BufferView * bv) const
4521 {
4522         InsetTabularMailer(*this).showDialog(bv);
4523 }
4524
4525
4526 bool InsetTabular::copySelection(Cursor & cur)
4527 {
4528         if (!cur.selection())
4529                 return false;
4530
4531         row_type rs, re;
4532         col_type cs, ce;
4533         getSelection(cur, rs, re, cs, ce);
4534
4535         paste_tabular.reset(new Tabular(tabular));
4536
4537         for (row_type i = 0; i < rs; ++i)
4538                 paste_tabular->deleteRow(0);
4539
4540         row_type const rows = re - rs + 1;
4541         while (paste_tabular->rowCount() > rows)
4542                 paste_tabular->deleteRow(rows);
4543
4544         paste_tabular->setTopLine(0, true, true);
4545         paste_tabular->setBottomLine(paste_tabular->getFirstCellInRow(rows - 1),
4546                                      true, true);
4547
4548         for (col_type i = 0; i < cs; ++i)
4549                 paste_tabular->deleteColumn(0);
4550
4551         col_type const columns = ce - cs + 1;
4552         while (paste_tabular->columnCount() > columns)
4553                 paste_tabular->deleteColumn(columns);
4554
4555         paste_tabular->setLeftLine(0, true, true);
4556         paste_tabular->setRightLine(paste_tabular->getLastCellInRow(0),
4557                                     true, true);
4558
4559         odocstringstream os;
4560         OutputParams const runparams(0);
4561         paste_tabular->plaintext(cur.buffer(), os, runparams, 0, true, '\t');
4562         // Needed for the "Edit->Paste recent" menu and the system clipboard.
4563         cap::copySelection(cur, os.str());
4564
4565         // mark tabular stack dirty
4566         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
4567         // when we (hopefully) have a one-for-all paste mechanism.
4568         // This must be called after cap::copySelection.
4569         dirtyTabularStack(true);
4570
4571         return true;
4572 }
4573
4574
4575 bool InsetTabular::pasteClipboard(Cursor & cur)
4576 {
4577         if (!paste_tabular)
4578                 return false;
4579         col_type const actcol = tabular.cellColumn(cur.idx());
4580         row_type const actrow = tabular.cellRow(cur.idx());
4581         for (row_type r1 = 0, r2 = actrow;
4582              r1 < paste_tabular->rowCount() && r2 < tabular.rowCount();
4583              ++r1, ++r2) {
4584                 for (col_type c1 = 0, c2 = actcol;
4585                     c1 < paste_tabular->columnCount() && c2 < tabular.columnCount();
4586                     ++c1, ++c2) {
4587                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
4588                             tabular.isPartOfMultiColumn(r2, c2))
4589                                 continue;
4590                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
4591                                 --c2;
4592                                 continue;
4593                         }
4594                         if (tabular.isPartOfMultiColumn(r2, c2)) {
4595                                 --c1;
4596                                 continue;
4597                         }
4598                         shared_ptr<InsetText> inset(
4599                                 new InsetText(*paste_tabular->getCellInset(r1, c1)));
4600                         tabular.setCellInset(r2, c2, inset);
4601                         // FIXME: change tracking (MG)
4602                         inset->setChange(Change(cur.buffer().params().trackChanges ?
4603                                                 Change::INSERTED : Change::UNCHANGED));
4604                         cur.pos() = 0;
4605                 }
4606         }
4607         return true;
4608 }
4609
4610
4611 void InsetTabular::cutSelection(Cursor & cur)
4612 {
4613         if (!cur.selection())
4614                 return;
4615
4616         row_type rs, re;
4617         col_type cs, ce;
4618         getSelection(cur, rs, re, cs, ce);
4619         for (row_type i = rs; i <= re; ++i) {
4620                 for (col_type j = cs; j <= ce; ++j) {
4621                         shared_ptr<InsetText> t
4622                                 = cell(tabular.cellIndex(i, j));
4623                         if (cur.buffer().params().trackChanges)
4624                                 // FIXME: Change tracking (MG)
4625                                 t->setChange(Change(Change::DELETED));
4626                         else
4627                                 t->clear();
4628                 }
4629         }
4630
4631         // cursor position might be invalid now
4632         if (cur.pit() > cur.lastpit())
4633                 cur.pit() = cur.lastpit();
4634         if (cur.pos() > cur.lastpos())
4635                 cur.pos() = cur.lastpos();
4636         cur.clearSelection();
4637 }
4638
4639
4640 bool InsetTabular::isRightToLeft(Cursor & cur) const
4641 {
4642         BOOST_ASSERT(cur.depth() > 1);
4643         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
4644         pos_type const parentpos = cur[cur.depth() - 2].pos();
4645         return parentpar.getFontSettings(cur.bv().buffer().params(),
4646                                          parentpos).language()->rightToLeft();
4647 }
4648
4649
4650 void InsetTabular::getSelection(Cursor & cur,
4651         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
4652 {
4653         CursorSlice const & beg = cur.selBegin();
4654         CursorSlice const & end = cur.selEnd();
4655         cs = tabular.cellColumn(beg.idx());
4656         ce = tabular.cellColumn(end.idx());
4657         if (cs > ce) {
4658                 ce = cs;
4659                 cs = tabular.cellColumn(end.idx());
4660         } else {
4661                 ce = tabular.cellRightColumn(end.idx());
4662         }
4663
4664         rs = tabular.cellRow(beg.idx());
4665         re = tabular.cellRow(end.idx());
4666         if (rs > re)
4667                 swap(rs, re);
4668 }
4669
4670
4671 Text * InsetTabular::getText(int idx) const
4672 {
4673         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
4674 }
4675
4676
4677 void InsetTabular::setChange(Change const & change)
4678 {
4679         for (idx_type idx = 0; idx < nargs(); ++idx)
4680                 cell(idx)->setChange(change);
4681 }
4682
4683
4684 void InsetTabular::acceptChanges(BufferParams const & bparams)
4685 {
4686         for (idx_type idx = 0; idx < nargs(); ++idx)
4687                 cell(idx)->acceptChanges(bparams);
4688 }
4689
4690
4691 void InsetTabular::rejectChanges(BufferParams const & bparams)
4692 {
4693         for (idx_type idx = 0; idx < nargs(); ++idx)
4694                 cell(idx)->rejectChanges(bparams);
4695 }
4696
4697
4698 bool InsetTabular::forceDefaultParagraphs(idx_type cell) const
4699 {
4700         return tabular.getPWidth(cell).zero();
4701 }
4702
4703
4704 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
4705                                      bool usePaste)
4706 {
4707         if (buf.length() <= 0)
4708                 return true;
4709
4710         Buffer const & buffer = bv.buffer();
4711
4712         col_type cols = 1;
4713         row_type rows = 1;
4714         col_type maxCols = 1;
4715         docstring::size_type const len = buf.length();
4716         docstring::size_type p = 0;
4717
4718         while (p < len &&
4719                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
4720                 switch (buf[p]) {
4721                 case '\t':
4722                         ++cols;
4723                         break;
4724                 case '\n':
4725                         if (p + 1 < len)
4726                                 ++rows;
4727                         maxCols = max(cols, maxCols);
4728                         cols = 1;
4729                         break;
4730                 }
4731                 ++p;
4732         }
4733         maxCols = max(cols, maxCols);
4734         Tabular * loctab;
4735         idx_type cell = 0;
4736         col_type ocol = 0;
4737         row_type row = 0;
4738         if (usePaste) {
4739                 paste_tabular.reset(
4740                         new Tabular(buffer.params(), rows, maxCols));
4741                 loctab = paste_tabular.get();
4742                 cols = 0;
4743                 dirtyTabularStack(true);
4744         } else {
4745                 loctab = &tabular;
4746                 cell = bv.cursor().idx();
4747                 ocol = tabular.cellColumn(cell);
4748                 row = tabular.cellRow(cell);
4749         }
4750
4751         docstring::size_type op = 0;
4752         idx_type const cells = loctab->cellCount();
4753         p = 0;
4754         cols = ocol;
4755         rows = loctab->rowCount();
4756         col_type const columns = loctab->columnCount();
4757
4758         while (cell < cells && p < len && row < rows &&
4759                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
4760         {
4761                 if (p >= len)
4762                         break;
4763                 switch (buf[p]) {
4764                 case '\t':
4765                         // we can only set this if we are not too far right
4766                         if (cols < columns) {
4767                                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
4768                                 Font const font = bv.textMetrics(&inset->text_).
4769                                         getDisplayFont(0, 0);
4770                                 inset->setText(buf.substr(op, p - op), font,
4771                                                buffer.params().trackChanges);
4772                                 ++cols;
4773                                 ++cell;
4774                         }
4775                         break;
4776                 case '\n':
4777                         // we can only set this if we are not too far right
4778                         if (cols < columns) {
4779                                 shared_ptr<InsetText> inset = tabular.getCellInset(cell);
4780                                 Font const font = bv.textMetrics(&inset->text_).
4781                                         getDisplayFont(0, 0);
4782                                 inset->setText(buf.substr(op, p - op), font,
4783                                                buffer.params().trackChanges);
4784                         }
4785                         cols = ocol;
4786                         ++row;
4787                         if (row < rows)
4788                                 cell = loctab->cellIndex(row, cols);
4789                         break;
4790                 }
4791                 ++p;
4792                 op = p;
4793         }
4794         // check for the last cell if there is no trailing '\n'
4795         if (cell < cells && op < len) {
4796                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
4797                 Font const font = bv.textMetrics(&inset->text_).getDisplayFont(0, 0);
4798                 inset->setText(buf.substr(op, len - op), font,
4799                         buffer.params().trackChanges);
4800         }
4801         return true;
4802 }
4803
4804
4805 void InsetTabular::addPreview(PreviewLoader & loader) const
4806 {
4807         row_type const rows = tabular.rowCount();
4808         col_type const columns = tabular.columnCount();
4809         for (row_type i = 0; i < rows; ++i) {
4810                 for (col_type j = 0; j < columns; ++j)
4811                         tabular.getCellInset(i, j)->addPreview(loader);
4812         }
4813 }
4814
4815
4816 bool InsetTabular::tablemode(Cursor & cur) const
4817 {
4818         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
4819 }
4820
4821
4822
4823
4824 string const InsetTabularMailer::name_("tabular");
4825
4826 InsetTabularMailer::InsetTabularMailer(InsetTabular const & inset)
4827         : inset_(const_cast<InsetTabular &>(inset))
4828 {}
4829
4830
4831 string const InsetTabularMailer::inset2string(Buffer const &) const
4832 {
4833         return params2string(inset_);
4834 }
4835
4836
4837 void InsetTabularMailer::string2params(string const & in, InsetTabular & inset)
4838 {
4839         istringstream data(in);
4840         Lexer lex(0,0);
4841         lex.setStream(data);
4842
4843         if (in.empty())
4844                 return;
4845
4846         string token;
4847         lex >> token;
4848         if (!lex || token != name_)
4849                 return print_mailer_error("InsetTabularMailer", in, 1,
4850                                           name_);
4851
4852         // This is part of the inset proper that is usually swallowed
4853         // by Buffer::readInset
4854         lex >> token;
4855         if (!lex || token != "Tabular")
4856                 return print_mailer_error("InsetTabularMailer", in, 2,
4857                                           "Tabular");
4858
4859         Buffer const & buffer = inset.buffer();
4860         inset.read(buffer, lex);
4861 }
4862
4863
4864 string const InsetTabularMailer::params2string(InsetTabular const & inset)
4865 {
4866         ostringstream data;
4867         data << name_ << ' ';
4868         inset.write(inset.buffer(), data);
4869         data << "\\end_inset\n";
4870         return data.str();
4871 }
4872
4873
4874 } // namespace lyx