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