]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
InsetTabular.cpp: check for top and bottom lines, fixes http://bugzilla.lyx.org/show_...
[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 && topLine(row)) {
1966                 os << "\\toprule ";
1967         } else if (tmp == n - fcell) {
1968                 os << (use_booktabs ? "\\midrule " : "\\hline ");
1969         } else if (tmp) {
1970                 for (idx_type i = fcell; i < n; ++i) {
1971                         if (topLine(i)) {
1972                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1973                                    << cellColumn(i) + 1
1974                                    << '-'
1975                                    << cellRightColumn(i) + 1
1976                                    << "} ";
1977                         }
1978                 }
1979         } else {
1980                 return 0;
1981         }
1982         os << "\n";
1983         return 1;
1984 }
1985
1986
1987 int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
1988 {
1989         // FIXME: return 0 or assert as in TeXTopHLine()?
1990         if (row == npos || row >= rowCount())
1991                 return 0;
1992
1993         idx_type const fcell = getFirstCellInRow(row);
1994         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1995         idx_type tmp = 0;
1996
1997         for (idx_type i = fcell; i < n; ++i) {
1998                 if (bottomLine(i))
1999                         ++tmp;
2000         }
2001         if (use_booktabs && row == rowCount() - 1 && bottomLine(row)) {
2002                 os << "\\bottomrule";
2003         } else if (tmp == n - fcell) {
2004                 os << (use_booktabs ? "\\midrule" : "\\hline");
2005         } else if (tmp) {
2006                 for (idx_type i = fcell; i < n; ++i) {
2007                         if (bottomLine(i)) {
2008                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
2009                                    << cellColumn(i) + 1
2010                                    << '-'
2011                                    << cellRightColumn(i) + 1
2012                                    << "} ";
2013                         }
2014                 }
2015         } else {
2016                 return 0;
2017         }
2018         os << "\n";
2019         return 1;
2020 }
2021
2022
2023 int Tabular::TeXCellPreamble(odocstream & os, idx_type cell) const
2024 {
2025         int ret = 0;
2026
2027         if (getRotateCell(cell)) {
2028                 os << "\\begin{sideways}\n";
2029                 ++ret;
2030         }
2031         if (isMultiColumn(cell)) {
2032                 os << "\\multicolumn{" << cells_in_multicolumn(cell) << "}{";
2033                 if (leftLine(cell) &&
2034                         (isFirstCellInRow(cell) ||
2035                          (!isMultiColumn(cell - 1) && !leftLine(cell, true) &&
2036                           !rightLine(cell - 1, true))))
2037                         os << '|';
2038                 if (!cellinfo_of_cell(cell).align_special.empty()) {
2039                         os << cellinfo_of_cell(cell).align_special;
2040                 } else {
2041                         if (!getPWidth(cell).zero()) {
2042                                 switch (getVAlignment(cell)) {
2043                                 case LYX_VALIGN_TOP:
2044                                         os << 'p';
2045                                         break;
2046                                 case LYX_VALIGN_MIDDLE:
2047                                         os << 'm';
2048                                         break;
2049                                 case LYX_VALIGN_BOTTOM:
2050                                         os << 'b';
2051                                         break;
2052                                 }
2053                                 os << '{'
2054                                    << from_ascii(getPWidth(cell).asLatexString())
2055                                    << '}';
2056                         } else {
2057                                 switch (getAlignment(cell)) {
2058                                 case LYX_ALIGN_LEFT:
2059                                         os << 'l';
2060                                         break;
2061                                 case LYX_ALIGN_RIGHT:
2062                                         os << 'r';
2063                                         break;
2064                                 default:
2065                                         os << 'c';
2066                                         break;
2067                                 }
2068                         } // end if else !getPWidth
2069                 } // end if else !cellinfo_of_cell
2070                 if (rightLine(cell))
2071                         os << '|';
2072                 if (((cell + 1) < cellCount()) && !isFirstCellInRow(cell+1) &&
2073                         leftLine(cell+1))
2074                         os << '|';
2075                 os << "}{";
2076                 }
2077         if (getUsebox(cell) == BOX_PARBOX) {
2078                 os << "\\parbox[";
2079                 switch (getVAlignment(cell)) {
2080                 case LYX_VALIGN_TOP:
2081                         os << 't';
2082                         break;
2083                 case LYX_VALIGN_MIDDLE:
2084                         os << 'c';
2085                         break;
2086                 case LYX_VALIGN_BOTTOM:
2087                         os << 'b';
2088                         break;
2089                 }
2090                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2091                    << "}{";
2092         } else if (getUsebox(cell) == BOX_MINIPAGE) {
2093                 os << "\\begin{minipage}[";
2094                 switch (getVAlignment(cell)) {
2095                 case LYX_VALIGN_TOP:
2096                         os << 't';
2097                         break;
2098                 case LYX_VALIGN_MIDDLE:
2099                         os << 'm';
2100                         break;
2101                 case LYX_VALIGN_BOTTOM:
2102                         os << 'b';
2103                         break;
2104                 }
2105                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2106                    << "}\n";
2107                 ++ret;
2108         }
2109         return ret;
2110 }
2111
2112
2113 int Tabular::TeXCellPostamble(odocstream & os, idx_type cell) const
2114 {
2115         int ret = 0;
2116
2117         // usual cells
2118         if (getUsebox(cell) == BOX_PARBOX)
2119                 os << '}';
2120         else if (getUsebox(cell) == BOX_MINIPAGE) {
2121                 os << "%\n\\end{minipage}";
2122                 ret += 2;
2123         }
2124         if (isMultiColumn(cell)) {
2125                 os << '}';
2126         }
2127         if (getRotateCell(cell)) {
2128                 os << "%\n\\end{sideways}";
2129                 ++ret;
2130         }
2131         return ret;
2132 }
2133
2134
2135 int Tabular::TeXLongtableHeaderFooter(odocstream & os, Buffer const & buf,
2136                                          OutputParams const & runparams) const
2137 {
2138         if (!is_long_tabular)
2139                 return 0;
2140
2141         int ret = 0;
2142         // output header info
2143         if (haveLTHead()) {
2144                 if (endhead.topDL) {
2145                         os << "\\hline\n";
2146                         ++ret;
2147                 }
2148                 for (row_type i = 0; i < rowCount(); ++i) {
2149                         if (row_info[i].endhead) {
2150                                 ret += TeXRow(os, i, buf, runparams);
2151                         }
2152                 }
2153                 if (endhead.bottomDL) {
2154                         os << "\\hline\n";
2155                         ++ret;
2156                 }
2157                 os << "\\endhead\n";
2158                 ++ret;
2159                 if (endfirsthead.empty) {
2160                         os << "\\endfirsthead\n";
2161                         ++ret;
2162                 }
2163         }
2164         // output firstheader info
2165         if (haveLTFirstHead()) {
2166                 if (endfirsthead.topDL) {
2167                         os << "\\hline\n";
2168                         ++ret;
2169                 }
2170                 for (row_type i = 0; i < rowCount(); ++i) {
2171                         if (row_info[i].endfirsthead) {
2172                                 ret += TeXRow(os, i, buf, runparams);
2173                         }
2174                 }
2175                 if (endfirsthead.bottomDL) {
2176                         os << "\\hline\n";
2177                         ++ret;
2178                 }
2179                 os << "\\endfirsthead\n";
2180                 ++ret;
2181         }
2182         // output footer info
2183         if (haveLTFoot()) {
2184                 if (endfoot.topDL) {
2185                         os << "\\hline\n";
2186                         ++ret;
2187                 }
2188                 for (row_type i = 0; i < rowCount(); ++i) {
2189                         if (row_info[i].endfoot) {
2190                                 ret += TeXRow(os, i, buf, runparams);
2191                         }
2192                 }
2193                 if (endfoot.bottomDL) {
2194                         os << "\\hline\n";
2195                         ++ret;
2196                 }
2197                 os << "\\endfoot\n";
2198                 ++ret;
2199                 if (endlastfoot.empty) {
2200                         os << "\\endlastfoot\n";
2201                         ++ret;
2202                 }
2203         }
2204         // output lastfooter info
2205         if (haveLTLastFoot()) {
2206                 if (endlastfoot.topDL) {
2207                         os << "\\hline\n";
2208                         ++ret;
2209                 }
2210                 for (row_type i = 0; i < rowCount(); ++i) {
2211                         if (row_info[i].endlastfoot) {
2212                                 ret += TeXRow(os, i, buf, runparams);
2213                         }
2214                 }
2215                 if (endlastfoot.bottomDL) {
2216                         os << "\\hline\n";
2217                         ++ret;
2218                 }
2219                 os << "\\endlastfoot\n";
2220                 ++ret;
2221         }
2222         return ret;
2223 }
2224
2225
2226 bool Tabular::isValidRow(row_type row) const
2227 {
2228         if (!is_long_tabular)
2229                 return true;
2230         return !row_info[row].endhead && !row_info[row].endfirsthead &&
2231                         !row_info[row].endfoot && !row_info[row].endlastfoot;
2232 }
2233
2234
2235 int Tabular::TeXRow(odocstream & os, row_type i, Buffer const & buf,
2236                        OutputParams const & runparams) const
2237 {
2238         idx_type cell = cellIndex(i, 0);
2239         int ret = TeXTopHLine(os, i);
2240         if (row_info[i].top_space_default) {
2241                 if (use_booktabs)
2242                         os << "\\addlinespace\n";
2243                 else
2244                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2245                 ++ret;
2246         } else if(!row_info[i].top_space.zero()) {
2247                 if (use_booktabs)
2248                         os << "\\addlinespace["
2249                            << from_ascii(row_info[i].top_space.asLatexString())
2250                            << "]\n";
2251                 else {
2252                         os << "\\noalign{\\vskip"
2253                            << from_ascii(row_info[i].top_space.asLatexString())
2254                            << "}\n";
2255                 }
2256                 ++ret;
2257         }
2258
2259         for (col_type j = 0; j < columnCount(); ++j) {
2260                 if (isPartOfMultiColumn(i, j))
2261                         continue;
2262                 ret += TeXCellPreamble(os, cell);
2263                 shared_ptr<InsetText> inset = getCellInset(cell);
2264
2265                 Paragraph const & par = inset->paragraphs().front();
2266                 bool rtl = par.isRTL(buf.params())
2267                         && !par.empty()
2268                         && getPWidth(cell).zero();
2269
2270                 if (rtl) {
2271                         if (par.getParLanguage(buf.params())->lang() ==
2272                         "farsi")
2273                                 os << "\\textFR{";
2274                         else if (par.getParLanguage(buf.params())->lang() == "arabic_arabi")
2275                                 os << "\\textAR{";
2276                         // currently, remaning RTL languages are arabic_arabtex and hebrew
2277                         else
2278                                 os << "\\R{";
2279                 }
2280                 ret += inset->latex(buf, os, runparams);
2281                 if (rtl)
2282                         os << '}';
2283
2284                 ret += TeXCellPostamble(os, cell);
2285                 if (!isLastCellInRow(cell)) { // not last cell in row
2286                         os << " & ";
2287                 }
2288                 ++cell;
2289         }
2290         os << "\\tabularnewline";
2291         if (row_info[i].bottom_space_default) {
2292                 if (use_booktabs)
2293                         os << "\\addlinespace";
2294                 else
2295                         os << "[\\doublerulesep]";
2296         } else if (!row_info[i].bottom_space.zero()) {
2297                 if (use_booktabs)
2298                         os << "\\addlinespace";
2299                 os << '['
2300                    << from_ascii(row_info[i].bottom_space.asLatexString())
2301                    << ']';
2302         }
2303         os << '\n';
2304         ++ret;
2305         ret += TeXBottomHLine(os, i);
2306         if (row_info[i].interline_space_default) {
2307                 if (use_booktabs)
2308                         os << "\\addlinespace\n";
2309                 else
2310                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2311                 ++ret;
2312         } else if (!row_info[i].interline_space.zero()) {
2313                 if (use_booktabs)
2314                         os << "\\addlinespace["
2315                            << from_ascii(row_info[i].interline_space.asLatexString())
2316                            << "]\n";
2317                 else
2318                         os << "\\noalign{\\vskip"
2319                            << from_ascii(row_info[i].interline_space.asLatexString())
2320                            << "}\n";
2321                 ++ret;
2322         }
2323         return ret;
2324 }
2325
2326
2327 int Tabular::latex(Buffer const & buf, odocstream & os,
2328                       OutputParams const & runparams) const
2329 {
2330         int ret = 0;
2331
2332         //+---------------------------------------------------------------------
2333         //+                      first the opening preamble                    +
2334         //+---------------------------------------------------------------------
2335
2336         if (rotate) {
2337                 os << "\\begin{sideways}\n";
2338                 ++ret;
2339         }
2340         if (is_long_tabular)
2341                 os << "\\begin{longtable}{";
2342         else
2343                 os << "\\begin{tabular}{";
2344         for (col_type i = 0; i < columnCount(); ++i) {
2345                 if (!use_booktabs && column_info[i].left_line)
2346                         os << '|';
2347                 if (!column_info[i].align_special.empty()) {
2348                         os << column_info[i].align_special;
2349                 } else {
2350                         if (!column_info[i].p_width.zero()) {
2351                                 switch (column_info[i].alignment) {
2352                                 case LYX_ALIGN_LEFT:
2353                                         os << ">{\\raggedright}";
2354                                         break;
2355                                 case LYX_ALIGN_RIGHT:
2356                                         os << ">{\\raggedleft}";
2357                                         break;
2358                                 case LYX_ALIGN_CENTER:
2359                                         os << ">{\\centering}";
2360                                         break;
2361                                 case LYX_ALIGN_NONE:
2362                                 case LYX_ALIGN_BLOCK:
2363                                 case LYX_ALIGN_LAYOUT:
2364                                 case LYX_ALIGN_SPECIAL:
2365                                         break;
2366                                 }
2367
2368                                 switch (column_info[i].valignment) {
2369                                 case LYX_VALIGN_TOP:
2370                                         os << 'p';
2371                                         break;
2372                                 case LYX_VALIGN_MIDDLE:
2373                                         os << 'm';
2374                                         break;
2375                                 case LYX_VALIGN_BOTTOM:
2376                                         os << 'b';
2377                                         break;
2378                         }
2379                                 os << '{'
2380                                    << from_ascii(column_info[i].p_width.asLatexString())
2381                                    << '}';
2382                         } else {
2383                                 switch (column_info[i].alignment) {
2384                                 case LYX_ALIGN_LEFT:
2385                                         os << 'l';
2386                                         break;
2387                                 case LYX_ALIGN_RIGHT:
2388                                         os << 'r';
2389                                         break;
2390                                 default:
2391                                         os << 'c';
2392                                         break;
2393                                 }
2394                         } // end if else !column_info[i].p_width
2395                 } // end if else !column_info[i].align_special
2396                 if (!use_booktabs && column_info[i].right_line)
2397                         os << '|';
2398         }
2399         os << "}\n";
2400         ++ret;
2401
2402         ret += TeXLongtableHeaderFooter(os, buf, runparams);
2403
2404         //+---------------------------------------------------------------------
2405         //+                      the single row and columns (cells)            +
2406         //+---------------------------------------------------------------------
2407
2408         for (row_type i = 0; i < rowCount(); ++i) {
2409                 if (isValidRow(i)) {
2410                         ret += TeXRow(os, i, buf, runparams);
2411                         if (is_long_tabular && row_info[i].newpage) {
2412                                 os << "\\newpage\n";
2413                                 ++ret;
2414                         }
2415                 }
2416         }
2417
2418         //+---------------------------------------------------------------------
2419         //+                      the closing of the tabular                    +
2420         //+---------------------------------------------------------------------
2421
2422         if (is_long_tabular)
2423                 os << "\\end{longtable}";
2424         else
2425                 os << "\\end{tabular}";
2426         if (rotate) {
2427                 os << "\n\\end{sideways}";
2428                 ++ret;
2429         }
2430
2431         return ret;
2432 }
2433
2434
2435 int Tabular::docbookRow(Buffer const & buf, odocstream & os, row_type row,
2436                            OutputParams const & runparams) const
2437 {
2438         int ret = 0;
2439         idx_type cell = getFirstCellInRow(row);
2440
2441         os << "<row>\n";
2442         for (col_type j = 0; j < columnCount(); ++j) {
2443                 if (isPartOfMultiColumn(row, j))
2444                         continue;
2445
2446                 os << "<entry align=\"";
2447                 switch (getAlignment(cell)) {
2448                 case LYX_ALIGN_LEFT:
2449                         os << "left";
2450                         break;
2451                 case LYX_ALIGN_RIGHT:
2452                         os << "right";
2453                         break;
2454                 default:
2455                         os << "center";
2456                         break;
2457                 }
2458
2459                 os << "\" valign=\"";
2460                 switch (getVAlignment(cell)) {
2461                 case LYX_VALIGN_TOP:
2462                         os << "top";
2463                         break;
2464                 case LYX_VALIGN_BOTTOM:
2465                         os << "bottom";
2466                         break;
2467                 case LYX_VALIGN_MIDDLE:
2468                         os << "middle";
2469                 }
2470                 os << '"';
2471
2472                 if (isMultiColumn(cell)) {
2473                         os << " namest=\"col" << j << "\" ";
2474                         os << "nameend=\"col" << j + cells_in_multicolumn(cell) - 1<< '"';
2475                 }
2476
2477                 os << '>';
2478                 ret += getCellInset(cell)->docbook(buf, os, runparams);
2479                 os << "</entry>\n";
2480                 ++cell;
2481         }
2482         os << "</row>\n";
2483         return ret;
2484 }
2485
2486
2487 int Tabular::docbook(Buffer const & buf, odocstream & os,
2488                         OutputParams const & runparams) const
2489 {
2490         int ret = 0;
2491
2492         //+---------------------------------------------------------------------
2493         //+                      first the opening preamble                    +
2494         //+---------------------------------------------------------------------
2495
2496         os << "<tgroup cols=\"" << columnCount()
2497            << "\" colsep=\"1\" rowsep=\"1\">\n";
2498
2499         for (col_type i = 0; i < columnCount(); ++i) {
2500                 os << "<colspec colname=\"col" << i << "\" align=\"";
2501                 switch (column_info[i].alignment) {
2502                 case LYX_ALIGN_LEFT:
2503                         os << "left";
2504                         break;
2505                 case LYX_ALIGN_RIGHT:
2506                         os << "right";
2507                         break;
2508                 default:
2509                         os << "center";
2510                         break;
2511                 }
2512                 os << '"';
2513                 if (runparams.flavor == OutputParams::XML)
2514                         os << '/';
2515                 os << ">\n";
2516                 ++ret;
2517         }
2518
2519         //+---------------------------------------------------------------------
2520         //+                      Long Tabular case                             +
2521         //+---------------------------------------------------------------------
2522
2523         // output header info
2524         if (haveLTHead() || haveLTFirstHead()) {
2525                 os << "<thead>\n";
2526                 ++ret;
2527                 for (row_type i = 0; i < rowCount(); ++i) {
2528                         if (row_info[i].endhead || row_info[i].endfirsthead) {
2529                                 ret += docbookRow(buf, os, i, runparams);
2530                         }
2531                 }
2532                 os << "</thead>\n";
2533                 ++ret;
2534         }
2535         // output footer info
2536         if (haveLTFoot() || haveLTLastFoot()) {
2537                 os << "<tfoot>\n";
2538                 ++ret;
2539                 for (row_type i = 0; i < rowCount(); ++i) {
2540                         if (row_info[i].endfoot || row_info[i].endlastfoot) {
2541                                 ret += docbookRow(buf, os, i, runparams);
2542                         }
2543                 }
2544                 os << "</tfoot>\n";
2545                 ++ret;
2546         }
2547
2548         //+---------------------------------------------------------------------
2549         //+                      the single row and columns (cells)            +
2550         //+---------------------------------------------------------------------
2551
2552         os << "<tbody>\n";
2553         ++ret;
2554         for (row_type i = 0; i < rowCount(); ++i) {
2555                 if (isValidRow(i)) {
2556                         ret += docbookRow(buf, os, i, runparams);
2557                 }
2558         }
2559         os << "</tbody>\n";
2560         ++ret;
2561         //+---------------------------------------------------------------------
2562         //+                      the closing of the tabular                    +
2563         //+---------------------------------------------------------------------
2564
2565         os << "</tgroup>";
2566         ++ret;
2567
2568         return ret;
2569 }
2570
2571
2572 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2573                                    vector<unsigned int> const & clen) const
2574 {
2575         idx_type const fcell = getFirstCellInRow(row);
2576         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2577         idx_type tmp = 0;
2578
2579         for (idx_type i = fcell; i < n; ++i) {
2580                 if (topLine(i)) {
2581                         ++tmp;
2582                         break;
2583                 }
2584         }
2585         if (!tmp)
2586                 return false;
2587
2588         char_type ch;
2589         for (idx_type i = fcell; i < n; ++i) {
2590                 if (topLine(i)) {
2591                         if (leftLine(i))
2592                                 os << "+-";
2593                         else
2594                                 os << "--";
2595                         ch = '-';
2596                 } else {
2597                         os << "  ";
2598                         ch = ' ';
2599                 }
2600                 col_type column = cellColumn(i);
2601                 int len = clen[column];
2602                 while (column < columnCount() - 1
2603                        && isPartOfMultiColumn(row, ++column))
2604                         len += clen[column] + 4;
2605                 os << docstring(len, ch);
2606                 if (topLine(i)) {
2607                         if (rightLine(i))
2608                                 os << "-+";
2609                         else
2610                                 os << "--";
2611                 } else {
2612                         os << "  ";
2613                 }
2614         }
2615         os << endl;
2616         return true;
2617 }
2618
2619
2620 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2621                                       vector<unsigned int> const & clen) const
2622 {
2623         idx_type const fcell = getFirstCellInRow(row);
2624         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2625         idx_type tmp = 0;
2626
2627         for (idx_type i = fcell; i < n; ++i) {
2628                 if (bottomLine(i)) {
2629                         ++tmp;
2630                         break;
2631                 }
2632         }
2633         if (!tmp)
2634                 return false;
2635
2636         char_type ch;
2637         for (idx_type i = fcell; i < n; ++i) {
2638                 if (bottomLine(i)) {
2639                         if (leftLine(i))
2640                                 os << "+-";
2641                         else
2642                                 os << "--";
2643                         ch = '-';
2644                 } else {
2645                         os << "  ";
2646                         ch = ' ';
2647                 }
2648                 col_type column = cellColumn(i);
2649                 int len = clen[column];
2650                 while (column < columnCount() -1
2651                        && isPartOfMultiColumn(row, ++column))
2652                         len += clen[column] + 4;
2653                 os << docstring(len, ch);
2654                 if (bottomLine(i)) {
2655                         if (rightLine(i))
2656                                 os << "-+";
2657                         else
2658                                 os << "--";
2659                 } else {
2660                         os << "  ";
2661                 }
2662         }
2663         os << endl;
2664         return true;
2665 }
2666
2667
2668 void Tabular::plaintextPrintCell(Buffer const & buf, odocstream & os,
2669                                OutputParams const & runparams,
2670                                idx_type cell, row_type row, col_type column,
2671                                vector<unsigned int> const & clen,
2672                                bool onlydata) const
2673 {
2674         odocstringstream sstr;
2675         getCellInset(cell)->plaintext(buf, sstr, runparams);
2676
2677         if (onlydata) {
2678                 os << sstr.str();
2679                 return;
2680         }
2681
2682         if (leftLine(cell))
2683                 os << "| ";
2684         else
2685                 os << "  ";
2686
2687         unsigned int len1 = sstr.str().length();
2688         unsigned int len2 = clen[column];
2689         while (column < columnCount() -1
2690                && isPartOfMultiColumn(row, ++column))
2691                 len2 += clen[column] + 4;
2692         len2 -= len1;
2693
2694         switch (getAlignment(cell)) {
2695         default:
2696         case LYX_ALIGN_LEFT:
2697                 len1 = 0;
2698                 break;
2699         case LYX_ALIGN_RIGHT:
2700                 len1 = len2;
2701                 len2 = 0;
2702                 break;
2703         case LYX_ALIGN_CENTER:
2704                 len1 = len2 / 2;
2705                 len2 -= len1;
2706                 break;
2707         }
2708
2709         os << docstring(len1, ' ') << sstr.str()
2710            << docstring(len2, ' ');
2711
2712         if (rightLine(cell))
2713                 os << " |";
2714         else
2715                 os << "  ";
2716 }
2717
2718
2719 void Tabular::plaintext(Buffer const & buf, odocstream & os,
2720                            OutputParams const & runparams, int const depth,
2721                            bool onlydata, char_type delim) const
2722 {
2723         // first calculate the width of the single columns
2724         vector<unsigned int> clen(columnCount());
2725
2726         if (!onlydata) {
2727                 // first all non (real) multicolumn cells!
2728                 for (col_type j = 0; j < columnCount(); ++j) {
2729                         clen[j] = 0;
2730                         for (row_type i = 0; i < rowCount(); ++i) {
2731                                 idx_type cell = cellIndex(i, j);
2732                                 if (isMultiColumnReal(cell))
2733                                         continue;
2734                                 odocstringstream sstr;
2735                                 getCellInset(cell)->plaintext(buf, sstr, runparams);
2736                                 if (clen[j] < sstr.str().length())
2737                                         clen[j] = sstr.str().length();
2738                         }
2739                 }
2740                 // then all (real) multicolumn cells!
2741                 for (col_type j = 0; j < columnCount(); ++j) {
2742                         for (row_type i = 0; i < rowCount(); ++i) {
2743                                 idx_type cell = cellIndex(i, j);
2744                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2745                                         continue;
2746                                 odocstringstream sstr;
2747                                 getCellInset(cell)->plaintext(buf, sstr, runparams);
2748                                 int len = int(sstr.str().length());
2749                                 idx_type const n = cells_in_multicolumn(cell);
2750                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2751                                         len -= clen[k];
2752                                 if (len > int(clen[j + n - 1]))
2753                                         clen[j + n - 1] = len;
2754                         }
2755                 }
2756         }
2757         idx_type cell = 0;
2758         for (row_type i = 0; i < rowCount(); ++i) {
2759                 if (!onlydata && plaintextTopHLine(os, i, clen))
2760                         os << docstring(depth * 2, ' ');
2761                 for (col_type j = 0; j < columnCount(); ++j) {
2762                         if (isPartOfMultiColumn(i, j))
2763                                 continue;
2764                         if (onlydata && j > 0)
2765                                 // we don't use operator<< for single UCS4 character.
2766                                 // see explanation in docstream.h
2767                                 os.put(delim);
2768                         plaintextPrintCell(buf, os, runparams,
2769                                            cell, i, j, clen, onlydata);
2770                         ++cell;
2771                 }
2772                 os << endl;
2773                 if (!onlydata) {
2774                         os << docstring(depth * 2, ' ');
2775                         if (plaintextBottomHLine(os, i, clen))
2776                                 os << docstring(depth * 2, ' ');
2777                 }
2778         }
2779 }
2780
2781
2782 shared_ptr<InsetText> Tabular::getCellInset(idx_type cell) const
2783 {
2784         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2785 }
2786
2787
2788 shared_ptr<InsetText> Tabular::getCellInset(row_type row,
2789                                                col_type column) const
2790 {
2791         return cell_info[row][column].inset;
2792 }
2793
2794
2795 void Tabular::setCellInset(row_type row, col_type column,
2796                               shared_ptr<InsetText> ins) const
2797 {
2798         cell_info[row][column].inset = ins;
2799 }
2800
2801
2802 Tabular::idx_type
2803 Tabular::getCellFromInset(Inset const * inset) const
2804 {
2805         // is this inset part of the tabular?
2806         if (!inset) {
2807                 lyxerr << "Error: this is not a cell of the tabular!" << endl;
2808                 BOOST_ASSERT(false);
2809         }
2810
2811         for (idx_type cell = 0, n = cellCount(); cell < n; ++cell)
2812                 if (getCellInset(cell).get() == inset) {
2813                         LYXERR(Debug::INSETTEXT, "Tabular::getCellFromInset: "
2814                                 << "cell=" << cell);
2815                         return cell;
2816                 }
2817
2818         // We should have found a cell at this point
2819         lyxerr << "Tabular::getCellFromInset: Cell of inset "
2820                 << inset << " not found!" << endl;
2821         BOOST_ASSERT(false);
2822         // shut up compiler
2823         return 0;
2824 }
2825
2826
2827 void Tabular::validate(LaTeXFeatures & features) const
2828 {
2829         features.require("NeedTabularnewline");
2830         if (useBookTabs())
2831                 features.require("booktabs");
2832         if (isLongTabular())
2833                 features.require("longtable");
2834         if (needRotating())
2835                 features.require("rotating");
2836         for (idx_type cell = 0; cell < cellCount(); ++cell) {
2837                 if (getVAlignment(cell) != LYX_VALIGN_TOP ||
2838                      (!getPWidth(cell).zero() && !isMultiColumn(cell)))
2839                         features.require("array");
2840                 getCellInset(cell)->validate(features);
2841         }
2842 }
2843
2844
2845 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2846 {
2847         ParagraphList const & parlist = getCellInset(cell)->paragraphs();
2848         ParagraphList::const_iterator cit = parlist.begin();
2849         ParagraphList::const_iterator end = parlist.end();
2850
2851         for (; cit != end; ++cit)
2852                 for (int i = 0; i < cit->size(); ++i)
2853                         if (cit->isNewline(i))
2854                                 return BOX_PARBOX;
2855
2856         return BOX_NONE;
2857 }
2858
2859
2860 /////////////////////////////////////////////////////////////////////
2861 //
2862 // InsetTabular
2863 //
2864 /////////////////////////////////////////////////////////////////////
2865
2866 InsetTabular::InsetTabular(Buffer const & buf, row_type rows,
2867                            col_type columns)
2868         : tabular(buf.params(), max(rows, row_type(1)),
2869           max(columns, col_type(1))), buffer_(&buf), scx_(0)
2870 {}
2871
2872
2873 InsetTabular::InsetTabular(InsetTabular const & tab)
2874         : Inset(tab), tabular(tab.tabular),
2875                 buffer_(tab.buffer_), scx_(0)
2876 {}
2877
2878
2879 InsetTabular::~InsetTabular()
2880 {
2881         InsetTabularMailer(*this).hideDialog();
2882 }
2883
2884
2885 Inset * InsetTabular::clone() const
2886 {
2887         return new InsetTabular(*this);
2888 }
2889
2890
2891 Buffer const & InsetTabular::buffer() const
2892 {
2893         return *buffer_;
2894 }
2895
2896
2897 void InsetTabular::buffer(Buffer const * b)
2898 {
2899         buffer_ = b;
2900 }
2901
2902
2903 bool InsetTabular::insetAllowed(InsetCode code) const
2904 {
2905         if (code == MATHMACRO_CODE)
2906                 return false;
2907
2908         return true;
2909 }
2910
2911
2912 void InsetTabular::write(Buffer const & buf, ostream & os) const
2913 {
2914         os << "Tabular" << endl;
2915         tabular.write(buf, os);
2916 }
2917
2918
2919 void InsetTabular::read(Buffer const & buf, Lexer & lex)
2920 {
2921         bool const old_format = (lex.getString() == "\\LyXTable");
2922
2923         tabular.read(buf, lex);
2924
2925         if (old_format)
2926                 return;
2927
2928         lex.next();
2929         string token = lex.getString();
2930         while (lex && token != "\\end_inset") {
2931                 lex.next();
2932                 token = lex.getString();
2933         }
2934         if (!lex) {
2935                 lex.printError("Missing \\end_inset at this point. "
2936                                "Read: `$$Token'");
2937         }
2938 }
2939
2940
2941 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
2942 {
2943         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
2944         //      mi.base.textwidth << "\n";
2945         if (!mi.base.bv) {
2946                 lyxerr << "InsetTabular::metrics: need bv" << endl;
2947                 BOOST_ASSERT(false);
2948         }
2949
2950         row_type i = 0;
2951         for (idx_type cell = 0; i < tabular.rowCount(); ++i) {
2952                 int maxAsc = 0;
2953                 int maxDesc = 0;
2954                 for (col_type j = 0; j < tabular.columnCount(); ++j) {
2955                         if (tabular.isPartOfMultiColumn(i, j))
2956                                 // Multicolumn cell, but not first one
2957                                 continue;
2958                         Dimension dim;
2959                         MetricsInfo m = mi;
2960                         Length p_width;
2961                         if (tabular.cell_info[i][j].multicolumn ==
2962                             Tabular::CELL_BEGIN_OF_MULTICOLUMN)
2963                                 p_width = tabular.cellinfo_of_cell(cell).p_width;
2964                         else
2965                                 p_width = tabular.column_info[j].p_width;
2966                         if (!p_width.zero())
2967                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
2968                         tabular.getCellInset(cell)->metrics(m, dim);
2969                         if (!p_width.zero())
2970                                 dim.wid = m.base.textwidth;
2971                         tabular.setCellWidth(cell, dim.wid);
2972                         if (p_width.zero()) {
2973                                 m.base.textwidth = dim.wid + 2 * ADD_TO_TABULAR_WIDTH;
2974                                 // FIXME there must be a way to get rid of
2975                                 // the second metrics call
2976                                 tabular.getCellInset(cell)->metrics(m, dim);
2977                         }
2978                         maxAsc  = max(maxAsc, dim.asc);
2979                         maxDesc = max(maxDesc, dim.des);
2980                         ++cell;
2981                 }
2982                 int const top_space = tabular.row_info[i].top_space_default ?
2983                         default_line_space :
2984                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
2985                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
2986                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
2987                         default_line_space :
2988                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
2989                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
2990         }
2991
2992         dim.asc = tabular.rowAscent(0);
2993         dim.des = tabular.height() - dim.asc;
2994         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
2995 }
2996
2997
2998 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
2999 {
3000         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
3001         BufferView * bv = pi.base.bv;
3002
3003         // FIXME: As the full backrgound is painted in drawSelection(),
3004         // we have no choice but to do a full repaint for the Text cells.
3005         pi.full_repaint = true;
3006
3007         resetPos(bv->cursor());
3008
3009         x += scx_;
3010         x += ADD_TO_TABULAR_WIDTH;
3011
3012         bool const original_drawing_state = pi.pain.isDrawingEnabled();
3013
3014         idx_type idx = 0;
3015         first_visible_cell = Tabular::npos;
3016         for (row_type i = 0; i < tabular.rowCount(); ++i) {
3017                 int nx = x;
3018                 int const a = tabular.rowAscent(i);
3019                 int const d = tabular.rowDescent(i);
3020                 idx = tabular.cellIndex(i, 0);
3021                 for (col_type j = 0; j < tabular.columnCount(); ++j) {
3022                         if (tabular.isPartOfMultiColumn(i, j))
3023                                 continue;
3024                         if (first_visible_cell == Tabular::npos)
3025                                 first_visible_cell = idx;
3026
3027                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
3028                         // Cache the Inset position.
3029                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
3030                         if (nx + tabular.columnWidth(idx) < 0
3031                             || nx > bv->workWidth()
3032                             || y + d < 0
3033                             || y - a > bv->workHeight()) {
3034                                 pi.pain.setDrawingEnabled(false);
3035                                 cell(idx)->draw(pi, cx, y);
3036                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
3037                                 pi.pain.setDrawingEnabled(original_drawing_state);
3038                         } else {
3039                                 cell(idx)->draw(pi, cx, y);
3040                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
3041                         }
3042                         nx += tabular.columnWidth(idx);
3043                         ++idx;
3044                 }
3045
3046                 if (i + 1 < tabular.rowCount())
3047                         y += d + tabular.rowAscent(i + 1) +
3048                                 tabular.getAdditionalHeight(i + 1);
3049         }
3050 }
3051
3052
3053 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3054 {
3055         Cursor & cur = pi.base.bv->cursor();
3056
3057         x += scx_ + ADD_TO_TABULAR_WIDTH;
3058
3059         // FIXME: it is wrong to completely paint the background
3060         // if we want to do single row painting.
3061
3062         // Paint background of current tabular
3063         int const w = tabular.width();
3064         int const h = tabular.height();
3065         int yy = y - tabular.rowAscent(0);
3066         pi.pain.fillRectangle(x, yy, w, h, backgroundColor());
3067
3068         if (!cur.selection())
3069                 return;
3070         if (&cur.inset() != this)
3071                 return;
3072
3073         //resetPos(cur);
3074
3075
3076         if (tablemode(cur)) {
3077                 row_type rs, re;
3078                 col_type cs, ce;
3079                 getSelection(cur, rs, re, cs, ce);
3080                 y -= tabular.rowAscent(0);
3081                 for (row_type j = 0; j < tabular.rowCount(); ++j) {
3082                         int const a = tabular.rowAscent(j);
3083                         int const h = a + tabular.rowDescent(j);
3084                         int xx = x;
3085                         y += tabular.getAdditionalHeight(j);
3086                         for (col_type i = 0; i < tabular.columnCount(); ++i) {
3087                                 if (tabular.isPartOfMultiColumn(j, i))
3088                                         continue;
3089                                 idx_type const cell =
3090                                         tabular.cellIndex(j, i);
3091                                 int const w = tabular.columnWidth(cell);
3092                                 if (i >= cs && i <= ce && j >= rs && j <= re)
3093                                         pi.pain.fillRectangle(xx, y, w, h,
3094                                                               Color_selection);
3095                                 xx += w;
3096                         }
3097                         y += h;
3098                 }
3099
3100         } else {
3101                 x += getCellXPos(cur.idx());
3102                 x += tabular.getBeginningOfTextInCell(cur.idx());
3103                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3104         }
3105 }
3106
3107
3108 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3109                                  row_type row, idx_type cell, bool erased) const
3110 {
3111         int x2 = x + tabular.columnWidth(cell);
3112         bool on_off = false;
3113         ColorCode col = Color_tabularline;
3114         ColorCode onoffcol = Color_tabularonoffline;
3115
3116         if (erased) {
3117                 col = Color_deletedtext;
3118                 onoffcol = Color_deletedtext;
3119         }
3120
3121         if (!tabular.topAlreadyDrawn(cell)) {
3122                 on_off = !tabular.topLine(cell);
3123                 pain.line(x, y - tabular.rowAscent(row),
3124                           x2, y -  tabular.rowAscent(row),
3125                           on_off ? onoffcol : col,
3126                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3127         }
3128         on_off = !tabular.bottomLine(cell);
3129         pain.line(x, y + tabular.rowDescent(row),
3130                   x2, y + tabular.rowDescent(row),
3131                   on_off ? onoffcol : col,
3132                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3133         if (!tabular.leftAlreadyDrawn(cell)) {
3134                 on_off = !tabular.leftLine(cell);
3135                 pain.line(x, y -  tabular.rowAscent(row),
3136                           x, y +  tabular.rowDescent(row),
3137                           on_off ? onoffcol : col,
3138                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3139         }
3140         on_off = !tabular.rightLine(cell);
3141         pain.line(x2 - tabular.getAdditionalWidth(cell),
3142                   y -  tabular.rowAscent(row),
3143                   x2 - tabular.getAdditionalWidth(cell),
3144                   y +  tabular.rowDescent(row),
3145                   on_off ? onoffcol : col,
3146                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3147 }
3148
3149
3150 docstring const InsetTabular::editMessage() const
3151 {
3152         return _("Opened table");
3153 }
3154
3155
3156 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3157 {
3158         //lyxerr << "InsetTabular::edit: " << this << endl;
3159         cur.finishUndo();
3160         cur.selection() = false;
3161         cur.push(*this);
3162         if (front) {
3163                 if (isRightToLeft(cur))
3164                         cur.idx() = tabular.getLastCellInRow(0);
3165                 else
3166                         cur.idx() = 0;
3167                 cur.pit() = 0;
3168                 cur.pos() = 0;
3169         } else {
3170                 if (isRightToLeft(cur))
3171                         cur.idx() = tabular.getFirstCellInRow(tabular.rowCount() - 1);
3172                 else
3173                         cur.idx() = tabular.cellCount() - 1;
3174                 cur.pit() = 0;
3175                 cur.pos() = cur.lastpos(); // FIXME crude guess
3176         }
3177         // FIXME: this accesses the position cache before it is initialized
3178         //resetPos(cur);
3179         //cur.bv().fitCursor();
3180 }
3181
3182
3183 void InsetTabular::updateLabels(Buffer const & buf, ParIterator const & it)
3184 {
3185         // In a longtable, tell captions what the current float is
3186         Counters & cnts = buf.params().getTextClass().counters();
3187         string const saveflt = cnts.current_float();
3188         if (tabular.isLongTabular())
3189                 cnts.current_float("table");
3190
3191         ParIterator it2 = it;
3192         it2.forwardPos();
3193         size_t const end = it2.nargs();
3194         for ( ; it2.idx() < end; it2.top().forwardIdx())
3195                 lyx::updateLabels(buf, it2);
3196
3197         //reset afterwards
3198         if (tabular.isLongTabular())
3199                 cnts.current_float(saveflt);
3200 }
3201
3202
3203 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3204 {
3205         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3206                              << "\n  cur:" << cur);
3207         CursorSlice sl = cur.top();
3208         Cursor & bvcur = cur.bv().cursor();
3209
3210         switch (cmd.action) {
3211
3212         case LFUN_MOUSE_PRESS:
3213                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3214
3215                 // do not reset cursor/selection if we have selected
3216                 // some cells (bug 2715).
3217                 if (cmd.button() == mouse_button::button3
3218                     && &bvcur.selBegin().inset() == this 
3219                     && tablemode(bvcur)) 
3220                         ;
3221                 else
3222                         // Let InsetText do it
3223                         cell(cur.idx())->dispatch(cur, cmd);
3224                 break;
3225         case LFUN_MOUSE_MOTION:
3226                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3227                 if (cmd.button() == mouse_button::button1) {
3228                         // only accept motions to places not deeper nested than the real anchor
3229                         if (bvcur.anchor_.hasPart(cur)) {
3230                                 // only update if selection changes
3231                                 if (bvcur.idx() == cur.idx() &&
3232                                         !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3233                                         cur.noUpdate();
3234                                 setCursorFromCoordinates(cur, cmd.x, cmd.y);
3235                                 bvcur.setCursor(cur);
3236                                 bvcur.selection() = true;
3237                         } else
3238                                 cur.undispatched();
3239                 }
3240                 break;
3241
3242         case LFUN_MOUSE_RELEASE:
3243                 //lyxerr << "# InsetTabular::MouseRelease\n" << bvcur << endl;
3244                 if (cmd.button() == mouse_button::button3)
3245                         InsetTabularMailer(*this).showDialog(&cur.bv());
3246                 break;
3247
3248         case LFUN_CELL_BACKWARD:
3249                 movePrevCell(cur);
3250                 cur.selection() = false;
3251                 break;
3252
3253         case LFUN_CELL_FORWARD:
3254                 moveNextCell(cur);
3255                 cur.selection() = false;
3256                 break;
3257
3258         case LFUN_CHAR_FORWARD_SELECT:
3259         case LFUN_CHAR_FORWARD:
3260                 cell(cur.idx())->dispatch(cur, cmd);
3261                 if (!cur.result().dispatched()) {
3262                         moveNextCell(cur);
3263                         if (sl == cur.top())
3264                                 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3265                         else
3266                                 cur.dispatched();
3267                 }
3268                 break;
3269
3270         case LFUN_CHAR_BACKWARD_SELECT:
3271         case LFUN_CHAR_BACKWARD:
3272                 cell(cur.idx())->dispatch(cur, cmd);
3273                 if (!cur.result().dispatched()) {
3274                         movePrevCell(cur);
3275                         if (sl == cur.top())
3276                                 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
3277                         else
3278                                 cur.dispatched();
3279                 }
3280                 break;
3281
3282         case LFUN_CHAR_RIGHT_SELECT:
3283         case LFUN_CHAR_RIGHT:
3284                 //FIXME: for visual cursor, really move right
3285                 if (isRightToLeft(cur))
3286                         lyx::dispatch(FuncRequest(
3287                                 cmd.action == LFUN_CHAR_RIGHT_SELECT ?
3288                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD));
3289                 else
3290                         lyx::dispatch(FuncRequest(
3291                                 cmd.action == LFUN_CHAR_RIGHT_SELECT ?
3292                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD));
3293                 break;
3294
3295         case LFUN_CHAR_LEFT_SELECT:
3296         case LFUN_CHAR_LEFT:
3297                 //FIXME: for visual cursor, really move left
3298                 if (isRightToLeft(cur))
3299                         lyx::dispatch(FuncRequest(
3300                                 cmd.action == LFUN_CHAR_LEFT_SELECT ?
3301                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD));
3302                 else
3303                         lyx::dispatch(FuncRequest(
3304                                 cmd.action == LFUN_CHAR_LEFT_SELECT ?
3305                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD));
3306                 break;
3307
3308         case LFUN_DOWN_SELECT:
3309         case LFUN_DOWN:
3310                 cell(cur.idx())->dispatch(cur, cmd);
3311                 cur.dispatched(); // override the cell's decision
3312                 if (sl == cur.top())
3313                         // if our Text didn't do anything to the cursor
3314                         // then we try to put the cursor into the cell below
3315                         // setting also the right targetX.
3316                         if (tabular.cellRow(cur.idx()) != tabular.rowCount() - 1) {
3317                                 cur.idx() = tabular.getCellBelow(cur.idx());
3318                                 cur.pit() = 0;
3319                                 TextMetrics const & tm =
3320                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3321                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3322                         }
3323                 if (sl == cur.top()) {
3324                         // we trick it to go to forward after leaving the
3325                         // tabular.
3326                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3327                         cur.undispatched();
3328                 }
3329                 break;
3330
3331         case LFUN_UP_SELECT:
3332         case LFUN_UP:
3333                 cell(cur.idx())->dispatch(cur, cmd);
3334                 cur.dispatched(); // override the cell's decision
3335                 if (sl == cur.top())
3336                         // if our Text didn't do anything to the cursor
3337                         // then we try to put the cursor into the cell above
3338                         // setting also the right targetX.
3339                         if (tabular.cellRow(cur.idx()) != 0) {
3340                                 cur.idx() = tabular.getCellAbove(cur.idx());
3341                                 cur.pit() = cur.lastpit();
3342                                 Text const * text = cell(cur.idx())->getText(0);
3343                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3344                                 ParagraphMetrics const & pm =
3345                                         tm.parMetrics(cur.lastpit());
3346                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3347                         }
3348                 if (sl == cur.top()) {
3349                         cmd = FuncRequest(LFUN_UP);
3350                         cur.undispatched();
3351                 }
3352                 break;
3353
3354 //      case LFUN_SCREEN_DOWN: {
3355 //              //if (hasSelection())
3356 //              //      cur.selection() = false;
3357 //              col_type const col = tabular.cellColumn(cur.idx());
3358 //              int const t =   cur.bv().top_y() + cur.bv().height();
3359 //              if (t < yo() + tabular.getHeightOfTabular()) {
3360 //                      cur.bv().scrollDocView(t);
3361 //                      cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
3362 //              } else {
3363 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3364 //              }
3365 //              cur.par() = 0;
3366 //              cur.pos() = 0;
3367 //              break;
3368 //      }
3369 //
3370 //      case LFUN_SCREEN_UP: {
3371 //              //if (hasSelection())
3372 //              //      cur.selection() = false;
3373 //              col_type const col = tabular.cellColumn(cur.idx());
3374 //              int const t =   cur.bv().top_y() + cur.bv().height();
3375 //              if (yo() < 0) {
3376 //                      cur.bv().scrollDocView(t);
3377 //                      if (yo() > 0)
3378 //                              cur.idx() = col;
3379 //                      else
3380 //                              cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
3381 //              } else {
3382 //                      cur.idx() = col;
3383 //              }
3384 //              cur.par() = cur.lastpar();
3385 //              cur.pos() = cur.lastpos();
3386 //              break;
3387 //      }
3388
3389         case LFUN_LAYOUT_TABULAR:
3390                 InsetTabularMailer(*this).showDialog(&cur.bv());
3391                 break;
3392
3393         case LFUN_INSET_DIALOG_UPDATE:
3394                 InsetTabularMailer(*this).updateDialog(&cur.bv());
3395                 break;
3396
3397         case LFUN_TABULAR_FEATURE:
3398                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3399                         cur.undispatched();
3400                 break;
3401
3402         // insert file functions
3403         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3404         case LFUN_FILE_INSERT_PLAINTEXT: {
3405                 // FIXME UNICODE
3406                 docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3407                         FileName(to_utf8(cmd.argument())));
3408                 if (tmpstr.empty())
3409                         break;
3410                 cur.recordUndoInset(INSERT_UNDO);
3411                 if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3412                         // content has been replaced,
3413                         // so cursor might be invalid
3414                         cur.pos() = cur.lastpos();
3415                         cur.pit() = cur.lastpit();
3416                         bvcur.setCursor(cur);
3417                 } else
3418                         cur.undispatched();
3419                 break;
3420         }
3421
3422         case LFUN_CUT:
3423                 if (tablemode(cur)) {
3424                         if (copySelection(cur)) {
3425                                 cur.recordUndoInset(DELETE_UNDO);
3426                                 cutSelection(cur);
3427                         }
3428                 }
3429                 else
3430                         cell(cur.idx())->dispatch(cur, cmd);
3431                 break;
3432
3433         case LFUN_CHAR_DELETE_BACKWARD:
3434         case LFUN_CHAR_DELETE_FORWARD:
3435                 if (tablemode(cur)) {
3436                         cur.recordUndoInset(DELETE_UNDO);
3437                         cutSelection(cur);
3438                 }
3439                 else
3440                         cell(cur.idx())->dispatch(cur, cmd);
3441                 break;
3442
3443         case LFUN_COPY:
3444                 if (!cur.selection())
3445                         break;
3446                 if (tablemode(cur)) {
3447                         cur.finishUndo();
3448                         copySelection(cur);
3449                 } else
3450                         cell(cur.idx())->dispatch(cur, cmd);
3451                 break;
3452
3453         case LFUN_CLIPBOARD_PASTE:
3454         case LFUN_PRIMARY_SELECTION_PASTE: {
3455                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3456                         theClipboard().getAsText() :
3457                         theSelection().get();
3458                 if (clip.empty())
3459                         break;
3460                 // pass to InsertPlaintextString, but
3461                 // only if we have multi-cell content
3462                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3463                         cur.recordUndoInset(INSERT_UNDO);
3464                         if (insertPlaintextString(cur.bv(), clip, false)) {
3465                                 // content has been replaced,
3466                                 // so cursor might be invalid
3467                                 cur.pos() = cur.lastpos();
3468                                 cur.pit() = cur.lastpit();
3469                                 bvcur.setCursor(cur);
3470                                 break;
3471                         }
3472                 }
3473                 // Let the cell handle normal text
3474                 cell(cur.idx())->dispatch(cur, cmd);
3475                 break;
3476         }
3477
3478         case LFUN_PASTE:
3479                 if (tabularStackDirty() && theClipboard().isInternal() ||
3480                     !theClipboard().hasInternal() && theClipboard().hasLyXContents()) {
3481                         cur.recordUndoInset(INSERT_UNDO);
3482                         pasteClipboard(cur);
3483                         break;
3484                 }
3485                 cell(cur.idx())->dispatch(cur, cmd);
3486                 break;
3487
3488         case LFUN_FONT_EMPH:
3489         case LFUN_FONT_BOLD:
3490         case LFUN_FONT_ROMAN:
3491         case LFUN_FONT_NOUN:
3492         case LFUN_FONT_ITAL:
3493         case LFUN_FONT_FRAK:
3494         case LFUN_FONT_TYPEWRITER:
3495         case LFUN_FONT_SANS:
3496         case LFUN_FONT_FREE_APPLY:
3497         case LFUN_FONT_FREE_UPDATE:
3498         case LFUN_FONT_SIZE:
3499         case LFUN_FONT_UNDERLINE:
3500         case LFUN_LANGUAGE:
3501         case LFUN_WORD_CAPITALIZE:
3502         case LFUN_WORD_UPCASE:
3503         case LFUN_WORD_LOWCASE:
3504         case LFUN_CHARS_TRANSPOSE:
3505                 if (tablemode(cur)) {
3506                         row_type rs, re;
3507                         col_type cs, ce;
3508                         getSelection(cur, rs, re, cs, ce);
3509                         Cursor tmpcur = cur;
3510                         for (row_type i = rs; i <= re; ++i) {
3511                                 for (col_type j = cs; j <= ce; ++j) {
3512                                         // cursor follows cell:
3513                                         tmpcur.idx() = tabular.cellIndex(i, j);
3514                                         // select this cell only:
3515                                         tmpcur.pit() = 0;
3516                                         tmpcur.pos() = 0;
3517                                         tmpcur.resetAnchor();
3518                                         tmpcur.pit() = tmpcur.lastpit();
3519                                         tmpcur.pos() = tmpcur.top().lastpos();
3520                                         tmpcur.setCursor(tmpcur);
3521                                         tmpcur.setSelection();
3522                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3523                                 }
3524                         }
3525                         break;
3526                 } else {
3527                         cell(cur.idx())->dispatch(cur, cmd);
3528                         break;
3529                 }
3530         default:
3531                 // we try to handle this event in the insets dispatch function.
3532                 cell(cur.idx())->dispatch(cur, cmd);
3533                 break;
3534         }
3535 }
3536
3537
3538 // function sets an object as defined in func_status.h:
3539 // states OK, Unknown, Disabled, On, Off.
3540 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3541         FuncStatus & status) const
3542 {
3543         switch (cmd.action) {
3544         case LFUN_TABULAR_FEATURE: {
3545                 int action = Tabular::LAST_ACTION;
3546                 int i = 0;
3547                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3548                         string const tmp = tabularFeature[i].feature;
3549                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3550                                 action = tabularFeature[i].action;
3551                                 break;
3552                         }
3553                 }
3554                 if (action == Tabular::LAST_ACTION) {
3555                         status.clear();
3556                         status.unknown(true);
3557                         return true;
3558                 }
3559
3560                 string const argument
3561                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3562
3563                 row_type sel_row_start = 0;
3564                 row_type sel_row_end = 0;
3565                 col_type sel_col_start = 0;
3566                 col_type sel_col_end = 0;
3567                 Tabular::ltType dummyltt;
3568                 bool flag = true;
3569
3570                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3571
3572                 switch (action) {
3573                 case Tabular::SET_PWIDTH:
3574                 case Tabular::SET_MPWIDTH:
3575                 case Tabular::SET_SPECIAL_COLUMN:
3576                 case Tabular::SET_SPECIAL_MULTI:
3577                 case Tabular::APPEND_ROW:
3578                 case Tabular::APPEND_COLUMN:
3579                 case Tabular::DELETE_ROW:
3580                 case Tabular::DELETE_COLUMN:
3581                 case Tabular::COPY_ROW:
3582                 case Tabular::COPY_COLUMN:
3583                 case Tabular::SET_ALL_LINES:
3584                 case Tabular::UNSET_ALL_LINES:
3585                 case Tabular::SET_TOP_SPACE:
3586                 case Tabular::SET_BOTTOM_SPACE:
3587                 case Tabular::SET_INTERLINE_SPACE:
3588                         status.clear();
3589                         return true;
3590
3591                 case Tabular::MULTICOLUMN:
3592                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3593                         break;
3594
3595                 case Tabular::M_TOGGLE_LINE_TOP:
3596                         flag = false;
3597                 case Tabular::TOGGLE_LINE_TOP:
3598                         status.setOnOff(tabular.topLine(cur.idx(), flag));
3599                         break;
3600
3601                 case Tabular::M_TOGGLE_LINE_BOTTOM:
3602                         flag = false;
3603                 case Tabular::TOGGLE_LINE_BOTTOM:
3604                         status.setOnOff(tabular.bottomLine(cur.idx(), flag));
3605                         break;
3606
3607                 case Tabular::M_TOGGLE_LINE_LEFT:
3608                         flag = false;
3609                 case Tabular::TOGGLE_LINE_LEFT:
3610                         status.setOnOff(tabular.leftLine(cur.idx(), flag));
3611                         break;
3612
3613                 case Tabular::M_TOGGLE_LINE_RIGHT:
3614                         flag = false;
3615                 case Tabular::TOGGLE_LINE_RIGHT:
3616                         status.setOnOff(tabular.rightLine(cur.idx(), flag));
3617                         break;
3618
3619                 case Tabular::M_ALIGN_LEFT:
3620                         flag = false;
3621                 case Tabular::ALIGN_LEFT:
3622                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3623                         break;
3624
3625                 case Tabular::M_ALIGN_RIGHT:
3626                         flag = false;
3627                 case Tabular::ALIGN_RIGHT:
3628                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3629                         break;
3630
3631                 case Tabular::M_ALIGN_CENTER:
3632                         flag = false;
3633                 case Tabular::ALIGN_CENTER:
3634                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3635                         break;
3636
3637                 case Tabular::ALIGN_BLOCK:
3638                         status.enabled(!tabular.getPWidth(cur.idx()).zero());
3639                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3640                         break;
3641
3642                 case Tabular::M_VALIGN_TOP:
3643                         flag = false;
3644                 case Tabular::VALIGN_TOP:
3645                         status.setOnOff(
3646                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3647                         break;
3648
3649                 case Tabular::M_VALIGN_BOTTOM:
3650                         flag = false;
3651                 case Tabular::VALIGN_BOTTOM:
3652                         status.setOnOff(
3653                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3654                         break;
3655
3656                 case Tabular::M_VALIGN_MIDDLE:
3657                         flag = false;
3658                 case Tabular::VALIGN_MIDDLE:
3659                         status.setOnOff(
3660                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3661                         break;
3662
3663                 case Tabular::SET_LONGTABULAR:
3664                         status.setOnOff(tabular.isLongTabular());
3665                         break;
3666
3667                 case Tabular::UNSET_LONGTABULAR:
3668                         status.setOnOff(!tabular.isLongTabular());
3669                         break;
3670
3671                 case Tabular::TOGGLE_ROTATE_TABULAR:
3672                 case Tabular::SET_ROTATE_TABULAR:
3673                         status.setOnOff(tabular.getRotateTabular());
3674                         break;
3675
3676                 case Tabular::UNSET_ROTATE_TABULAR:
3677                         status.setOnOff(!tabular.getRotateTabular());
3678                         break;
3679
3680                 case Tabular::TOGGLE_ROTATE_CELL:
3681                 case Tabular::SET_ROTATE_CELL:
3682                         status.setOnOff(!oneCellHasRotationState(false,
3683                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3684                         break;
3685
3686                 case Tabular::UNSET_ROTATE_CELL:
3687                         status.setOnOff(!oneCellHasRotationState(true,
3688                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3689                         break;
3690
3691                 case Tabular::SET_USEBOX:
3692                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
3693                         break;
3694
3695                 case Tabular::SET_LTFIRSTHEAD:
3696                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3697                         break;
3698
3699                 case Tabular::UNSET_LTFIRSTHEAD:
3700                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3701                         break;
3702
3703                 case Tabular::SET_LTHEAD:
3704                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3705                         break;
3706
3707                 case Tabular::UNSET_LTHEAD:
3708                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3709                         break;
3710
3711                 case Tabular::SET_LTFOOT:
3712                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3713                         break;
3714
3715                 case Tabular::UNSET_LTFOOT:
3716                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3717                         break;
3718
3719                 case Tabular::SET_LTLASTFOOT:
3720                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3721                         break;
3722
3723                 case Tabular::UNSET_LTLASTFOOT:
3724                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3725                         break;
3726
3727                 case Tabular::SET_LTNEWPAGE:
3728                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
3729                         break;
3730
3731                 case Tabular::SET_BOOKTABS:
3732                         status.setOnOff(tabular.useBookTabs());
3733                         break;
3734
3735                 case Tabular::UNSET_BOOKTABS:
3736                         status.setOnOff(!tabular.useBookTabs());
3737                         break;
3738
3739                 default:
3740                         status.clear();
3741                         status.enabled(false);
3742                         break;
3743                 }
3744                 return true;
3745         }
3746
3747         // These are only enabled inside tabular
3748         case LFUN_CELL_BACKWARD:
3749         case LFUN_CELL_FORWARD:
3750                 status.enabled(true);
3751                 return true;
3752
3753         // disable these with multiple cells selected
3754         case LFUN_INSET_INSERT:
3755         case LFUN_TABULAR_INSERT:
3756         case LFUN_FLEX_INSERT:
3757         case LFUN_FLOAT_INSERT:
3758         case LFUN_FLOAT_WIDE_INSERT:
3759         case LFUN_FOOTNOTE_INSERT:
3760         case LFUN_MARGINALNOTE_INSERT:
3761         case LFUN_MATH_INSERT:
3762         case LFUN_MATH_MODE:
3763         case LFUN_MATH_MUTATE:
3764         case LFUN_MATH_DISPLAY:
3765         case LFUN_NOTE_INSERT:
3766         case LFUN_OPTIONAL_INSERT:
3767         case LFUN_BOX_INSERT:
3768         case LFUN_BRANCH_INSERT:
3769         case LFUN_WRAP_INSERT:
3770         case LFUN_ERT_INSERT: {
3771                 if (tablemode(cur)) {
3772                         status.enabled(false);
3773                         return true;
3774                 } else
3775                         return cell(cur.idx())->getStatus(cur, cmd, status);
3776         }
3777
3778         // disable in non-fixed-width cells
3779         case LFUN_NEW_LINE:
3780         case LFUN_BREAK_PARAGRAPH:
3781         case LFUN_BREAK_PARAGRAPH_SKIP: {
3782                 if (tabular.getPWidth(cur.idx()).zero()) {
3783                         status.enabled(false);
3784                         return true;
3785                 } else
3786                         return cell(cur.idx())->getStatus(cur, cmd, status);
3787         }
3788
3789         case LFUN_PASTE:
3790                 if (tabularStackDirty() && theClipboard().isInternal()) {
3791                         status.enabled(true);
3792                         return true;
3793                 } else
3794                         return cell(cur.idx())->getStatus(cur, cmd, status);
3795
3796         case LFUN_INSET_MODIFY:
3797                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
3798                         status.enabled(true);
3799                         return true;
3800                 }
3801                 // Fall through
3802
3803         default:
3804                 // we try to handle this event in the insets dispatch function.
3805                 return cell(cur.idx())->getStatus(cur, cmd, status);
3806         }
3807 }
3808
3809
3810 int InsetTabular::latex(Buffer const & buf, odocstream & os,
3811                         OutputParams const & runparams) const
3812 {
3813         return tabular.latex(buf, os, runparams);
3814 }
3815
3816
3817 int InsetTabular::plaintext(Buffer const & buf, odocstream & os,
3818                             OutputParams const & runparams) const
3819 {
3820         os << '\n'; // output table on a new line
3821         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
3822         tabular.plaintext(buf, os, runparams, dp, false, 0);
3823         return PLAINTEXT_NEWLINE;
3824 }
3825
3826
3827 int InsetTabular::docbook(Buffer const & buf, odocstream & os,
3828                           OutputParams const & runparams) const
3829 {
3830         int ret = 0;
3831         Inset * master = 0;
3832
3833         // FIXME: Why not pass a proper DocIterator here?
3834 #if 0
3835         // if the table is inside a float it doesn't need the informaltable
3836         // wrapper. Search for it.
3837         for (master = owner(); master; master = master->owner())
3838                 if (master->lyxCode() == FLOAT_CODE)
3839                         break;
3840 #endif
3841
3842         if (!master) {
3843                 os << "<informaltable>";
3844                 ++ret;
3845         }
3846         ret += tabular.docbook(buf, os, runparams);
3847         if (!master) {
3848                 os << "</informaltable>";
3849                 ++ret;
3850         }
3851         return ret;
3852 }
3853
3854
3855 void InsetTabular::validate(LaTeXFeatures & features) const
3856 {
3857         tabular.validate(features);
3858 }
3859
3860
3861 shared_ptr<InsetText const> InsetTabular::cell(idx_type idx) const
3862 {
3863         return tabular.getCellInset(idx);
3864 }
3865
3866
3867 shared_ptr<InsetText> InsetTabular::cell(idx_type idx)
3868 {
3869         return tabular.getCellInset(idx);
3870 }
3871
3872
3873 void InsetTabular::cursorPos(BufferView const & bv,
3874                 CursorSlice const & sl, bool boundary, int & x, int & y) const
3875 {
3876         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
3877
3878         // y offset     correction
3879         int const row = tabular.cellRow(sl.idx());
3880         for (int i = 0; i <= row; ++i) {
3881                 if (i != 0) {
3882                         y += tabular.rowAscent(i);
3883                         y += tabular.getAdditionalHeight(i);
3884                 }
3885                 if (i != row)
3886                         y += tabular.rowDescent(i);
3887         }
3888
3889         // x offset correction
3890         int const col = tabular.cellColumn(sl.idx());
3891         int idx = tabular.cellIndex(row, 0);
3892         for (int j = 0; j < col; ++j) {
3893                 if (tabular.isPartOfMultiColumn(row, j))
3894                         continue;
3895                 x += tabular.columnWidth(idx);
3896                 ++idx;
3897         }
3898         x += tabular.getBeginningOfTextInCell(idx);
3899         x += ADD_TO_TABULAR_WIDTH;
3900         x += scx_;
3901 }
3902
3903
3904 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
3905 {
3906         int xx = 0;
3907         int yy = 0;
3908         Inset const & inset = *tabular.getCellInset(cell);
3909         Point o = bv.coordCache().getInsets().xy(&inset);
3910         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
3911         int const xend = xbeg + tabular.columnWidth(cell);
3912         row_type const row = tabular.cellRow(cell);
3913         int const ybeg = o.y_ - tabular.rowAscent(row) -
3914                          tabular.getAdditionalHeight(row);
3915         int const yend = o.y_ + tabular.rowDescent(row);
3916
3917         if (x < xbeg)
3918                 xx = xbeg - x;
3919         else if (x > xend)
3920                 xx = x - xend;
3921
3922         if (y < ybeg)
3923                 yy = ybeg - y;
3924         else if (y > yend)
3925                 yy = y - yend;
3926
3927         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
3928         //       << " ybeg=" << ybeg << " yend=" << yend
3929         //       << " xx=" << xx << " yy=" << yy
3930         //       << " dist=" << xx + yy << endl;
3931         return xx + yy;
3932 }
3933
3934
3935 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
3936 {
3937         //lyxerr << "InsetTabular::editXY: " << this << endl;
3938         cur.selection() = false;
3939         cur.push(*this);
3940         cur.idx() = getNearestCell(cur.bv(), x, y);
3941         resetPos(cur);
3942         return cur.bv().textMetrics(&cell(cur.idx())->text_).editXY(cur, x, y);
3943 }
3944
3945
3946 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
3947 {
3948         cur.idx() = getNearestCell(cur.bv(), x, y);
3949         cur.bv().textMetrics(&cell(cur.idx())->text_).setCursorFromCoordinates(cur, x, y);
3950 }
3951
3952
3953 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
3954 {
3955         idx_type idx_min = 0;
3956         int dist_min = numeric_limits<int>::max();
3957         for (idx_type i = 0, n = nargs(); i != n; ++i) {
3958                 if (bv.coordCache().getInsets().has(tabular.getCellInset(i).get())) {
3959                         int const d = dist(bv, i, x, y);
3960                         if (d < dist_min) {
3961                                 dist_min = d;
3962                                 idx_min = i;
3963                         }
3964                 }
3965         }
3966         return idx_min;
3967 }
3968
3969
3970 int InsetTabular::getCellXPos(idx_type const cell) const
3971 {
3972         idx_type c = cell;
3973
3974         for (; !tabular.isFirstCellInRow(c); --c)
3975                 ;
3976         int lx = 0;
3977         for (; c < cell; ++c)
3978                 lx += tabular.columnWidth(c);
3979
3980         return lx;
3981 }
3982
3983
3984 void InsetTabular::resetPos(Cursor & cur) const
3985 {
3986         BufferView & bv = cur.bv();
3987         int const maxwidth = bv.workWidth();
3988
3989         if (&cur.inset() != this) {
3990                 scx_ = 0;
3991         } else {
3992                 int const X1 = 0;
3993                 int const X2 = maxwidth;
3994                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
3995                 int const x1 = xo(cur.bv()) + getCellXPos(cur.idx()) + offset;
3996                 int const x2 = x1 + tabular.columnWidth(cur.idx());
3997
3998                 if (x1 < X1)
3999                         scx_ = X1 + 20 - x1;
4000                 else if (x2 > X2)
4001                         scx_ = X2 - 20 - x2;
4002                 else
4003                         scx_ = 0;
4004         }
4005
4006         cur.updateFlags(Update::Force | Update::FitCursor);
4007 }
4008
4009
4010 void InsetTabular::moveNextCell(Cursor & cur)
4011 {
4012         if (isRightToLeft(cur)) {
4013                 if (tabular.isFirstCellInRow(cur.idx())) {
4014                         row_type const row = tabular.cellRow(cur.idx());
4015                         if (row == tabular.rowCount() - 1)
4016                                 return;
4017                         cur.idx() = tabular.getCellBelow(tabular.getLastCellInRow(row));
4018                 } else {
4019                         if (cur.idx() == 0)
4020                                 return;
4021                         --cur.idx();
4022                 }
4023         } else {
4024                 if (tabular.isLastCell(cur.idx()))
4025                         return;
4026                 ++cur.idx();
4027         }
4028         cur.pit() = 0;
4029         cur.pos() = 0;
4030         resetPos(cur);
4031 }
4032
4033
4034 void InsetTabular::movePrevCell(Cursor & cur)
4035 {
4036         if (isRightToLeft(cur)) {
4037                 if (tabular.isLastCellInRow(cur.idx())) {
4038                         row_type const row = tabular.cellRow(cur.idx());
4039                         if (row == 0)
4040                                 return;
4041                         cur.idx() = tabular.getFirstCellInRow(row);
4042                         cur.idx() = tabular.getCellAbove(cur.idx());
4043                 } else {
4044                         if (tabular.isLastCell(cur.idx()))
4045                                 return;
4046                         ++cur.idx();
4047                 }
4048         } else {
4049                 if (cur.idx() == 0) // first cell
4050                         return;
4051                 --cur.idx();
4052         }
4053         cur.pit() = cur.lastpit();
4054         cur.pos() = cur.lastpos();
4055
4056         // FIXME: this accesses the position cache before it is initialized
4057         //resetPos(cur);
4058 }
4059
4060
4061 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4062 {
4063         Tabular::Feature action = Tabular::LAST_ACTION;
4064
4065         int i = 0;
4066         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4067                 string const tmp = tabularFeature[i].feature;
4068
4069                 if (tmp == what.substr(0, tmp.length())) {
4070                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4071                         //tabularFeatures[i].feature.length()))
4072                         action = tabularFeature[i].action;
4073                         break;
4074                 }
4075         }
4076         if (action == Tabular::LAST_ACTION)
4077                 return false;
4078
4079         string const val =
4080                 ltrim(what.substr(tabularFeature[i].feature.length()));
4081         tabularFeatures(cur, action, val);
4082         return true;
4083 }
4084
4085
4086 static void checkLongtableSpecial(Tabular::ltType & ltt,
4087                           string const & special, bool & flag)
4088 {
4089         if (special == "dl_above") {
4090                 ltt.topDL = flag;
4091                 ltt.set = false;
4092         } else if (special == "dl_below") {
4093                 ltt.bottomDL = flag;
4094                 ltt.set = false;
4095         } else if (special == "empty") {
4096                 ltt.empty = flag;
4097                 ltt.set = false;
4098         } else if (flag) {
4099                 ltt.empty = false;
4100                 ltt.set = true;
4101         }
4102 }
4103
4104 bool InsetTabular::oneCellHasRotationState(bool rotated,
4105                 row_type row_start, row_type row_end,
4106                 col_type col_start, col_type col_end) const {
4107
4108         for (row_type i = row_start; i <= row_end; ++i) {
4109                 for (col_type j = col_start; j <= col_end; ++j) {
4110                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4111                                 == rotated) {
4112                                 return true;
4113                         }
4114                 }
4115         }
4116         return false;
4117 }
4118
4119 void InsetTabular::tabularFeatures(Cursor & cur,
4120         Tabular::Feature feature, string const & value)
4121 {
4122         BufferView & bv = cur.bv();
4123         col_type sel_col_start;
4124         col_type sel_col_end;
4125         row_type sel_row_start;
4126         row_type sel_row_end;
4127         bool setLines = false;
4128         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4129         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4130
4131         switch (feature) {
4132
4133         case Tabular::M_ALIGN_LEFT:
4134         case Tabular::ALIGN_LEFT:
4135                 setAlign = LYX_ALIGN_LEFT;
4136                 break;
4137
4138         case Tabular::M_ALIGN_RIGHT:
4139         case Tabular::ALIGN_RIGHT:
4140                 setAlign = LYX_ALIGN_RIGHT;
4141                 break;
4142
4143         case Tabular::M_ALIGN_CENTER:
4144         case Tabular::ALIGN_CENTER:
4145                 setAlign = LYX_ALIGN_CENTER;
4146                 break;
4147
4148         case Tabular::ALIGN_BLOCK:
4149                 setAlign = LYX_ALIGN_BLOCK;
4150                 break;
4151
4152         case Tabular::M_VALIGN_TOP:
4153         case Tabular::VALIGN_TOP:
4154                 setVAlign = Tabular::LYX_VALIGN_TOP;
4155                 break;
4156
4157         case Tabular::M_VALIGN_BOTTOM:
4158         case Tabular::VALIGN_BOTTOM:
4159                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4160                 break;
4161
4162         case Tabular::M_VALIGN_MIDDLE:
4163         case Tabular::VALIGN_MIDDLE:
4164                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4165                 break;
4166
4167         default:
4168                 break;
4169         }
4170
4171         cur.recordUndoInset(ATOMIC_UNDO);
4172
4173         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4174         row_type const row = tabular.cellRow(cur.idx());
4175         col_type const column = tabular.cellColumn(cur.idx());
4176         bool flag = true;
4177         Tabular::ltType ltt;
4178
4179         switch (feature) {
4180
4181         case Tabular::SET_PWIDTH: {
4182                 Length const len(value);
4183                 tabular.setColumnPWidth(cur, cur.idx(), len);
4184                 if (len.zero()
4185                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4186                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4187                 break;
4188         }
4189
4190         case Tabular::SET_MPWIDTH:
4191                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4192                 break;
4193
4194         case Tabular::SET_SPECIAL_COLUMN:
4195         case Tabular::SET_SPECIAL_MULTI:
4196                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4197                 break;
4198
4199         case Tabular::APPEND_ROW:
4200                 // append the row into the tabular
4201                 tabular.appendRow(bv.buffer().params(), cur.idx());
4202                 break;
4203
4204         case Tabular::APPEND_COLUMN:
4205                 // append the column into the tabular
4206                 tabular.appendColumn(bv.buffer().params(), cur.idx());
4207                 cur.idx() = tabular.cellIndex(row, column);
4208                 break;
4209
4210         case Tabular::DELETE_ROW:
4211                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4212                         tabular.deleteRow(sel_row_start);
4213                 if (sel_row_start >= tabular.rowCount())
4214                         --sel_row_start;
4215                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4216                 cur.pit() = 0;
4217                 cur.pos() = 0;
4218                 cur.selection() = false;
4219                 break;
4220
4221         case Tabular::DELETE_COLUMN:
4222                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4223                         tabular.deleteColumn(sel_col_start);
4224                 if (sel_col_start >= tabular.columnCount())
4225                         --sel_col_start;
4226                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4227                 cur.pit() = 0;
4228                 cur.pos() = 0;
4229                 cur.selection() = false;
4230                 break;
4231
4232         case Tabular::COPY_ROW:
4233                 tabular.copyRow(bv.buffer().params(), row);
4234                 break;
4235
4236         case Tabular::COPY_COLUMN:
4237                 tabular.copyColumn(bv.buffer().params(), column);
4238                 cur.idx() = tabular.cellIndex(row, column);
4239                 break;
4240
4241         case Tabular::M_TOGGLE_LINE_TOP:
4242                 flag = false;
4243         case Tabular::TOGGLE_LINE_TOP: {
4244                 bool lineSet = !tabular.topLine(cur.idx(), flag);
4245                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4246                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4247                                 tabular.setTopLine(
4248                                         tabular.cellIndex(i, j),
4249                                         lineSet, flag);
4250                 break;
4251         }
4252
4253         case Tabular::M_TOGGLE_LINE_BOTTOM:
4254                 flag = false;
4255         case Tabular::TOGGLE_LINE_BOTTOM: {
4256                 bool lineSet = !tabular.bottomLine(cur.idx(), flag);
4257                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4258                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4259                                 tabular.setBottomLine(
4260                                         tabular.cellIndex(i, j),
4261                                         lineSet,
4262                                         flag);
4263                 break;
4264         }
4265
4266         case Tabular::M_TOGGLE_LINE_LEFT:
4267                 flag = false;
4268         case Tabular::TOGGLE_LINE_LEFT: {
4269                 bool lineSet = !tabular.leftLine(cur.idx(), flag);
4270                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4271                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4272                                 tabular.setLeftLine(
4273                                         tabular.cellIndex(i,j),
4274                                         lineSet,
4275                                         flag);
4276                 break;
4277         }
4278
4279         case Tabular::M_TOGGLE_LINE_RIGHT:
4280                 flag = false;
4281         case Tabular::TOGGLE_LINE_RIGHT: {
4282                 bool lineSet = !tabular.rightLine(cur.idx(), flag);
4283                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4284                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4285                                 tabular.setRightLine(
4286                                         tabular.cellIndex(i,j),
4287                                         lineSet,
4288                                         flag);
4289                 break;
4290         }
4291
4292         case Tabular::M_ALIGN_LEFT:
4293         case Tabular::M_ALIGN_RIGHT:
4294         case Tabular::M_ALIGN_CENTER:
4295                 flag = false;
4296         case Tabular::ALIGN_LEFT:
4297         case Tabular::ALIGN_RIGHT:
4298         case Tabular::ALIGN_CENTER:
4299         case Tabular::ALIGN_BLOCK:
4300                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4301                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4302                                 tabular.setAlignment(
4303                                         tabular.cellIndex(i, j),
4304                                         setAlign,
4305                                         flag);
4306                 break;
4307
4308         case Tabular::M_VALIGN_TOP:
4309         case Tabular::M_VALIGN_BOTTOM:
4310         case Tabular::M_VALIGN_MIDDLE:
4311                 flag = false;
4312         case Tabular::VALIGN_TOP:
4313         case Tabular::VALIGN_BOTTOM:
4314         case Tabular::VALIGN_MIDDLE:
4315                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4316                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4317                                 tabular.setVAlignment(
4318                                         tabular.cellIndex(i, j),
4319                                         setVAlign, flag);
4320                 break;
4321
4322         case Tabular::MULTICOLUMN: {
4323                 if (sel_row_start != sel_row_end) {
4324                         // FIXME: Need I say it ? This is horrible.
4325                         // FIXME UNICODE
4326                         Alert::error(_("Error setting multicolumn"),
4327                                      _("You cannot set multicolumn vertically."));
4328                         return;
4329                 }
4330                 if (!cur.selection()) {
4331                         // just multicol for one single cell
4332                         // check whether we are completely in a multicol
4333                         if (tabular.isMultiColumn(cur.idx()))
4334                                 tabular.unsetMultiColumn(cur.idx());
4335                         else
4336                                 tabular.setMultiColumn(&bv.buffer(), cur.idx(), 1);
4337                         break;
4338                 }
4339                 // we have a selection so this means we just add all this
4340                 // cells to form a multicolumn cell
4341                 idx_type const s_start = cur.selBegin().idx();
4342                 idx_type const s_end = cur.selEnd().idx();
4343                 tabular.setMultiColumn(&bv.buffer(), s_start, s_end - s_start + 1);
4344                 cur.idx() = s_start;
4345                 cur.pit() = 0;
4346                 cur.pos() = 0;
4347                 cur.selection() = false;
4348                 break;
4349         }
4350
4351         case Tabular::SET_ALL_LINES:
4352                 setLines = true;
4353         case Tabular::UNSET_ALL_LINES:
4354                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4355                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4356                                 tabular.setAllLines(
4357                                         tabular.cellIndex(i,j), setLines);
4358                 break;
4359
4360         case Tabular::SET_LONGTABULAR:
4361                 tabular.setLongTabular(true);
4362                 break;
4363
4364         case Tabular::UNSET_LONGTABULAR:
4365                 tabular.setLongTabular(false);
4366                 break;
4367
4368         case Tabular::SET_ROTATE_TABULAR:
4369                 tabular.setRotateTabular(true);
4370                 break;
4371
4372         case Tabular::UNSET_ROTATE_TABULAR:
4373                 tabular.setRotateTabular(false);
4374                 break;
4375
4376         case Tabular::TOGGLE_ROTATE_TABULAR:
4377                 tabular.setRotateTabular(!tabular.getRotateTabular());
4378                 break;
4379
4380         case Tabular::SET_ROTATE_CELL:
4381                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4382                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4383                                 tabular.setRotateCell(
4384                                         tabular.cellIndex(i, j), true);
4385                 break;
4386
4387         case Tabular::UNSET_ROTATE_CELL:
4388                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4389                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4390                                 tabular.setRotateCell(
4391                                         tabular.cellIndex(i, j), false);
4392                 break;
4393
4394         case Tabular::TOGGLE_ROTATE_CELL:
4395                 {
4396                 bool oneNotRotated = oneCellHasRotationState(false,
4397                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4398
4399                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4400                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4401                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4402                                                                           oneNotRotated);
4403                 }
4404                 break;
4405
4406         case Tabular::SET_USEBOX: {
4407                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4408                 if (val == tabular.getUsebox(cur.idx()))
4409                         val = Tabular::BOX_NONE;
4410                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4411                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4412                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4413                 break;
4414         }
4415
4416         case Tabular::UNSET_LTFIRSTHEAD:
4417                 flag = false;
4418         case Tabular::SET_LTFIRSTHEAD:
4419                 tabular.getRowOfLTFirstHead(row, ltt);
4420                 checkLongtableSpecial(ltt, value, flag);
4421                 tabular.setLTHead(row, flag, ltt, true);
4422                 break;
4423
4424         case Tabular::UNSET_LTHEAD:
4425                 flag = false;
4426         case Tabular::SET_LTHEAD:
4427                 tabular.getRowOfLTHead(row, ltt);
4428                 checkLongtableSpecial(ltt, value, flag);
4429                 tabular.setLTHead(row, flag, ltt, false);
4430                 break;
4431
4432         case Tabular::UNSET_LTFOOT:
4433                 flag = false;
4434         case Tabular::SET_LTFOOT:
4435                 tabular.getRowOfLTFoot(row, ltt);
4436                 checkLongtableSpecial(ltt, value, flag);
4437                 tabular.setLTFoot(row, flag, ltt, false);
4438                 break;
4439
4440         case Tabular::UNSET_LTLASTFOOT:
4441                 flag = false;
4442         case Tabular::SET_LTLASTFOOT:
4443                 tabular.getRowOfLTLastFoot(row, ltt);
4444                 checkLongtableSpecial(ltt, value, flag);
4445                 tabular.setLTFoot(row, flag, ltt, true);
4446                 break;
4447
4448         case Tabular::SET_LTNEWPAGE:
4449                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4450                 break;
4451
4452         case Tabular::SET_BOOKTABS:
4453                 tabular.setBookTabs(true);
4454                 break;
4455
4456         case Tabular::UNSET_BOOKTABS:
4457                 tabular.setBookTabs(false);
4458                 break;
4459
4460         case Tabular::SET_TOP_SPACE: {
4461                 Length len;
4462                 if (value == "default")
4463                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4464                                 tabular.row_info[i].top_space_default = true;
4465                 else if (isValidLength(value, &len))
4466                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4467                                 tabular.row_info[i].top_space_default = false;
4468                                 tabular.row_info[i].top_space = len;
4469                         }
4470                 else
4471                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4472                                 tabular.row_info[i].top_space_default = false;
4473                                 tabular.row_info[i].top_space = len;
4474                         }
4475                 break;
4476         }
4477
4478         case Tabular::SET_BOTTOM_SPACE: {
4479                 Length len;
4480                 if (value == "default")
4481                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4482                                 tabular.row_info[i].bottom_space_default = true;
4483                 else if (isValidLength(value, &len))
4484                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4485                                 tabular.row_info[i].bottom_space_default = false;
4486                                 tabular.row_info[i].bottom_space = len;
4487                         }
4488                 else
4489                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4490                                 tabular.row_info[i].bottom_space_default = false;
4491                                 tabular.row_info[i].bottom_space = len;
4492                         }
4493                 break;
4494         }
4495
4496         case Tabular::SET_INTERLINE_SPACE: {
4497                 Length len;
4498                 if (value == "default")
4499                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4500                                 tabular.row_info[i].interline_space_default = true;
4501                 else if (isValidLength(value, &len))
4502                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4503                                 tabular.row_info[i].interline_space_default = false;
4504                                 tabular.row_info[i].interline_space = len;
4505                         }
4506                 else
4507                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4508                                 tabular.row_info[i].interline_space_default = false;
4509                                 tabular.row_info[i].interline_space = len;
4510                         }
4511                 break;
4512         }
4513
4514         // dummy stuff just to avoid warnings
4515         case Tabular::LAST_ACTION:
4516                 break;
4517         }
4518 }
4519
4520
4521 bool InsetTabular::showInsetDialog(BufferView * bv) const
4522 {
4523         InsetTabularMailer(*this).showDialog(bv);
4524         return true;
4525 }
4526
4527
4528 void InsetTabular::openLayoutDialog(BufferView * bv) const
4529 {
4530         InsetTabularMailer(*this).showDialog(bv);
4531 }
4532
4533
4534 bool InsetTabular::copySelection(Cursor & cur)
4535 {
4536         if (!cur.selection())
4537                 return false;
4538
4539         row_type rs, re;
4540         col_type cs, ce;
4541         getSelection(cur, rs, re, cs, ce);
4542
4543         paste_tabular.reset(new Tabular(tabular));
4544
4545         for (row_type i = 0; i < rs; ++i)
4546                 paste_tabular->deleteRow(0);
4547
4548         row_type const rows = re - rs + 1;
4549         while (paste_tabular->rowCount() > rows)
4550                 paste_tabular->deleteRow(rows);
4551
4552         paste_tabular->setTopLine(0, true, true);
4553         paste_tabular->setBottomLine(paste_tabular->getFirstCellInRow(rows - 1),
4554                                      true, true);
4555
4556         for (col_type i = 0; i < cs; ++i)
4557                 paste_tabular->deleteColumn(0);
4558
4559         col_type const columns = ce - cs + 1;
4560         while (paste_tabular->columnCount() > columns)
4561                 paste_tabular->deleteColumn(columns);
4562
4563         paste_tabular->setLeftLine(0, true, true);
4564         paste_tabular->setRightLine(paste_tabular->getLastCellInRow(0),
4565                                     true, true);
4566
4567         odocstringstream os;
4568         OutputParams const runparams(0);
4569         paste_tabular->plaintext(cur.buffer(), os, runparams, 0, true, '\t');
4570         // Needed for the "Edit->Paste recent" menu and the system clipboard.
4571         cap::copySelection(cur, os.str());
4572
4573         // mark tabular stack dirty
4574         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
4575         // when we (hopefully) have a one-for-all paste mechanism.
4576         // This must be called after cap::copySelection.
4577         dirtyTabularStack(true);
4578
4579         return true;
4580 }
4581
4582
4583 bool InsetTabular::pasteClipboard(Cursor & cur)
4584 {
4585         if (!paste_tabular)
4586                 return false;
4587         col_type const actcol = tabular.cellColumn(cur.idx());
4588         row_type const actrow = tabular.cellRow(cur.idx());
4589         for (row_type r1 = 0, r2 = actrow;
4590              r1 < paste_tabular->rowCount() && r2 < tabular.rowCount();
4591              ++r1, ++r2) {
4592                 for (col_type c1 = 0, c2 = actcol;
4593                     c1 < paste_tabular->columnCount() && c2 < tabular.columnCount();
4594                     ++c1, ++c2) {
4595                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
4596                             tabular.isPartOfMultiColumn(r2, c2))
4597                                 continue;
4598                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
4599                                 --c2;
4600                                 continue;
4601                         }
4602                         if (tabular.isPartOfMultiColumn(r2, c2)) {
4603                                 --c1;
4604                                 continue;
4605                         }
4606                         shared_ptr<InsetText> inset(
4607                                 new InsetText(*paste_tabular->getCellInset(r1, c1)));
4608                         tabular.setCellInset(r2, c2, inset);
4609                         // FIXME: change tracking (MG)
4610                         inset->setChange(Change(cur.buffer().params().trackChanges ?
4611                                                 Change::INSERTED : Change::UNCHANGED));
4612                         cur.pos() = 0;
4613                 }
4614         }
4615         return true;
4616 }
4617
4618
4619 void InsetTabular::cutSelection(Cursor & cur)
4620 {
4621         if (!cur.selection())
4622                 return;
4623
4624         row_type rs, re;
4625         col_type cs, ce;
4626         getSelection(cur, rs, re, cs, ce);
4627         for (row_type i = rs; i <= re; ++i) {
4628                 for (col_type j = cs; j <= ce; ++j) {
4629                         shared_ptr<InsetText> t
4630                                 = cell(tabular.cellIndex(i, j));
4631                         if (cur.buffer().params().trackChanges)
4632                                 // FIXME: Change tracking (MG)
4633                                 t->setChange(Change(Change::DELETED));
4634                         else
4635                                 t->clear();
4636                 }
4637         }
4638
4639         // cursor position might be invalid now
4640         if (cur.pit() > cur.lastpit())
4641                 cur.pit() = cur.lastpit();
4642         if (cur.pos() > cur.lastpos())
4643                 cur.pos() = cur.lastpos();
4644         cur.clearSelection();
4645 }
4646
4647
4648 bool InsetTabular::isRightToLeft(Cursor & cur) const
4649 {
4650         BOOST_ASSERT(cur.depth() > 1);
4651         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
4652         pos_type const parentpos = cur[cur.depth() - 2].pos();
4653         return parentpar.getFontSettings(cur.bv().buffer().params(),
4654                                          parentpos).language()->rightToLeft();
4655 }
4656
4657
4658 void InsetTabular::getSelection(Cursor & cur,
4659         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
4660 {
4661         CursorSlice const & beg = cur.selBegin();
4662         CursorSlice const & end = cur.selEnd();
4663         cs = tabular.cellColumn(beg.idx());
4664         ce = tabular.cellColumn(end.idx());
4665         if (cs > ce) {
4666                 ce = cs;
4667                 cs = tabular.cellColumn(end.idx());
4668         } else {
4669                 ce = tabular.cellRightColumn(end.idx());
4670         }
4671
4672         rs = tabular.cellRow(beg.idx());
4673         re = tabular.cellRow(end.idx());
4674         if (rs > re)
4675                 swap(rs, re);
4676 }
4677
4678
4679 Text * InsetTabular::getText(int idx) const
4680 {
4681         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
4682 }
4683
4684
4685 void InsetTabular::setChange(Change const & change)
4686 {
4687         for (idx_type idx = 0; idx < nargs(); ++idx)
4688                 cell(idx)->setChange(change);
4689 }
4690
4691
4692 void InsetTabular::acceptChanges(BufferParams const & bparams)
4693 {
4694         for (idx_type idx = 0; idx < nargs(); ++idx)
4695                 cell(idx)->acceptChanges(bparams);
4696 }
4697
4698
4699 void InsetTabular::rejectChanges(BufferParams const & bparams)
4700 {
4701         for (idx_type idx = 0; idx < nargs(); ++idx)
4702                 cell(idx)->rejectChanges(bparams);
4703 }
4704
4705
4706 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
4707 {
4708         return tabular.getPWidth(cell).zero();
4709 }
4710
4711
4712 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
4713                                      bool usePaste)
4714 {
4715         if (buf.length() <= 0)
4716                 return true;
4717
4718         Buffer const & buffer = bv.buffer();
4719
4720         col_type cols = 1;
4721         row_type rows = 1;
4722         col_type maxCols = 1;
4723         docstring::size_type const len = buf.length();
4724         docstring::size_type p = 0;
4725
4726         while (p < len &&
4727                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
4728                 switch (buf[p]) {
4729                 case '\t':
4730                         ++cols;
4731                         break;
4732                 case '\n':
4733                         if (p + 1 < len)
4734                                 ++rows;
4735                         maxCols = max(cols, maxCols);
4736                         cols = 1;
4737                         break;
4738                 }
4739                 ++p;
4740         }
4741         maxCols = max(cols, maxCols);
4742         Tabular * loctab;
4743         idx_type cell = 0;
4744         col_type ocol = 0;
4745         row_type row = 0;
4746         if (usePaste) {
4747                 paste_tabular.reset(
4748                         new Tabular(buffer.params(), rows, maxCols));
4749                 loctab = paste_tabular.get();
4750                 cols = 0;
4751                 dirtyTabularStack(true);
4752         } else {
4753                 loctab = &tabular;
4754                 cell = bv.cursor().idx();
4755                 ocol = tabular.cellColumn(cell);
4756                 row = tabular.cellRow(cell);
4757         }
4758
4759         docstring::size_type op = 0;
4760         idx_type const cells = loctab->cellCount();
4761         p = 0;
4762         cols = ocol;
4763         rows = loctab->rowCount();
4764         col_type const columns = loctab->columnCount();
4765
4766         while (cell < cells && p < len && row < rows &&
4767                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
4768         {
4769                 if (p >= len)
4770                         break;
4771                 switch (buf[p]) {
4772                 case '\t':
4773                         // we can only set this if we are not too far right
4774                         if (cols < columns) {
4775                                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
4776                                 Font const font = bv.textMetrics(&inset->text_).
4777                                         getDisplayFont(0, 0);
4778                                 inset->setText(buf.substr(op, p - op), font,
4779                                                buffer.params().trackChanges);
4780                                 ++cols;
4781                                 ++cell;
4782                         }
4783                         break;
4784                 case '\n':
4785                         // we can only set this if we are not too far right
4786                         if (cols < columns) {
4787                                 shared_ptr<InsetText> inset = tabular.getCellInset(cell);
4788                                 Font const font = bv.textMetrics(&inset->text_).
4789                                         getDisplayFont(0, 0);
4790                                 inset->setText(buf.substr(op, p - op), font,
4791                                                buffer.params().trackChanges);
4792                         }
4793                         cols = ocol;
4794                         ++row;
4795                         if (row < rows)
4796                                 cell = loctab->cellIndex(row, cols);
4797                         break;
4798                 }
4799                 ++p;
4800                 op = p;
4801         }
4802         // check for the last cell if there is no trailing '\n'
4803         if (cell < cells && op < len) {
4804                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
4805                 Font const font = bv.textMetrics(&inset->text_).getDisplayFont(0, 0);
4806                 inset->setText(buf.substr(op, len - op), font,
4807                         buffer.params().trackChanges);
4808         }
4809         return true;
4810 }
4811
4812
4813 void InsetTabular::addPreview(PreviewLoader & loader) const
4814 {
4815         row_type const rows = tabular.rowCount();
4816         col_type const columns = tabular.columnCount();
4817         for (row_type i = 0; i < rows; ++i) {
4818                 for (col_type j = 0; j < columns; ++j)
4819                         tabular.getCellInset(i, j)->addPreview(loader);
4820         }
4821 }
4822
4823
4824 bool InsetTabular::tablemode(Cursor & cur) const
4825 {
4826         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
4827 }
4828
4829
4830
4831
4832 string const InsetTabularMailer::name_("tabular");
4833
4834 InsetTabularMailer::InsetTabularMailer(InsetTabular const & inset)
4835         : inset_(const_cast<InsetTabular &>(inset))
4836 {}
4837
4838
4839 string const InsetTabularMailer::inset2string(Buffer const &) const
4840 {
4841         return params2string(inset_);
4842 }
4843
4844
4845 void InsetTabularMailer::string2params(string const & in, InsetTabular & inset)
4846 {
4847         istringstream data(in);
4848         Lexer lex(0,0);
4849         lex.setStream(data);
4850
4851         if (in.empty())
4852                 return;
4853
4854         string token;
4855         lex >> token;
4856         if (!lex || token != name_)
4857                 return print_mailer_error("InsetTabularMailer", in, 1,
4858                                           name_);
4859
4860         // This is part of the inset proper that is usually swallowed
4861         // by Buffer::readInset
4862         lex >> token;
4863         if (!lex || token != "Tabular")
4864                 return print_mailer_error("InsetTabularMailer", in, 2,
4865                                           "Tabular");
4866
4867         Buffer const & buffer = inset.buffer();
4868         inset.read(buffer, lex);
4869 }
4870
4871
4872 string const InsetTabularMailer::params2string(InsetTabular const & inset)
4873 {
4874         ostringstream data;
4875         data << name_ << ' ';
4876         inset.write(inset.buffer(), data);
4877         data << "\\end_inset\n";
4878         return data.str();
4879 }
4880
4881
4882 } // namespace lyx