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