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