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