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