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