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