]> git.lyx.org Git - features.git/blob - src/insets/InsetTabular.cpp
Disable setting vertical lines when using a formal table
[features.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Matthias Ettrich
8  * \author José Matos
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Jürgen Vigna
14  * \author Uwe Stöhr
15  * \author Edwin Leuven
16  * \author Scott Kostyshak
17  *
18  * Full author contact details are available in file CREDITS.
19  */
20
21 #include <config.h>
22
23 #include "InsetTabular.h"
24
25 #include "buffer_funcs.h"
26 #include "Buffer.h"
27 #include "BufferParams.h"
28 #include "BufferView.h"
29 #include "CoordCache.h"
30 #include "Counters.h"
31 #include "Cursor.h"
32 #include "CutAndPaste.h"
33 #include "DispatchResult.h"
34 #include "FuncRequest.h"
35 #include "FuncStatus.h"
36 #include "InsetList.h"
37 #include "Language.h"
38 #include "LaTeXFeatures.h"
39 #include "Lexer.h"
40 #include "LyX.h"
41 #include "LyXRC.h"
42 #include "MetricsInfo.h"
43 #include "OutputParams.h"
44 #include "output_xhtml.h"
45 #include "Paragraph.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "TextClass.h"
49 #include "TextMetrics.h"
50
51 #include "frontends/Application.h"
52 #include "frontends/alert.h"
53 #include "frontends/Clipboard.h"
54 #include "frontends/Painter.h"
55 #include "frontends/Selection.h"
56
57 #include "support/convert.h"
58 #include "support/debug.h"
59 #include "support/docstream.h"
60 #include "support/FileName.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/lstrings.h"
64
65 #include <boost/scoped_ptr.hpp>
66
67 #include <cstring>
68 #include <iostream>
69 #include <limits>
70 #include <sstream>
71
72 using namespace std;
73 using namespace lyx::support;
74
75
76
77 namespace lyx {
78
79 using cap::dirtyTabularStack;
80 using cap::tabularStackDirty;
81
82 using graphics::PreviewLoader;
83
84 using frontend::Painter;
85 using frontend::Clipboard;
86
87 namespace Alert = frontend::Alert;
88
89
90 namespace {
91
92 int const ADD_TO_HEIGHT = 2; // in cell
93 int const ADD_TO_TABULAR_WIDTH = 6; // horizontal space before and after the table
94 int const default_line_space = 10; // ?
95 int const WIDTH_OF_LINE = 5; // space between double lines
96
97
98 ///
99 boost::scoped_ptr<Tabular> paste_tabular;
100
101
102 struct TabularFeature {
103         Tabular::Feature action;
104         string feature;
105         bool need_value;
106 };
107
108
109 TabularFeature tabularFeature[] =
110 {
111         // the SET/UNSET actions are used by the table dialog,
112         // the TOGGLE actions by the table toolbar buttons
113         { Tabular::APPEND_ROW, "append-row", false },
114         { Tabular::APPEND_COLUMN, "append-column", false },
115         { Tabular::DELETE_ROW, "delete-row", false },
116         { Tabular::DELETE_COLUMN, "delete-column", false },
117         { Tabular::COPY_ROW, "copy-row", false },
118         { Tabular::COPY_COLUMN, "copy-column", false },
119         { Tabular::MOVE_COLUMN_RIGHT, "move-column-right", false },
120         { Tabular::MOVE_COLUMN_LEFT, "move-column-left", false },
121         { Tabular::MOVE_ROW_DOWN, "move-row-down", false },
122         { Tabular::MOVE_ROW_UP, "move-row-up", false },
123         { Tabular::SET_LINE_TOP, "set-line-top", true },
124         { Tabular::SET_LINE_BOTTOM, "set-line-bottom", true },
125         { Tabular::SET_LINE_LEFT, "set-line-left", true },
126         { Tabular::SET_LINE_RIGHT, "set-line-right", true },
127         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top", false },
128         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom", false },
129         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left", false },
130         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right", false },
131         { Tabular::ALIGN_LEFT, "align-left", false },
132         { Tabular::ALIGN_RIGHT, "align-right", false },
133         { Tabular::ALIGN_CENTER, "align-center", false },
134         { Tabular::ALIGN_BLOCK, "align-block", false },
135         { Tabular::ALIGN_DECIMAL, "align-decimal", false },
136         { Tabular::VALIGN_TOP, "valign-top", false },
137         { Tabular::VALIGN_BOTTOM, "valign-bottom", false },
138         { Tabular::VALIGN_MIDDLE, "valign-middle", false },
139         { Tabular::M_ALIGN_LEFT, "m-align-left", false },
140         { Tabular::M_ALIGN_RIGHT, "m-align-right", false },
141         { Tabular::M_ALIGN_CENTER, "m-align-center", false },
142         { Tabular::M_VALIGN_TOP, "m-valign-top", false },
143         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom", false },
144         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle", false },
145         { Tabular::MULTICOLUMN, "multicolumn", false },
146         { Tabular::SET_MULTICOLUMN, "set-multicolumn", false },
147         { Tabular::UNSET_MULTICOLUMN, "unset-multicolumn", false },
148         { Tabular::MULTIROW, "multirow", false },
149         { Tabular::SET_MULTIROW, "set-multirow", false },
150         { Tabular::UNSET_MULTIROW, "unset-multirow", false },
151         { Tabular::SET_MROFFSET, "set-mroffset", true },
152         { Tabular::SET_ALL_LINES, "set-all-lines", false },
153         { Tabular::UNSET_ALL_LINES, "unset-all-lines", false },
154         { Tabular::SET_LONGTABULAR, "set-longtabular", false },
155         { Tabular::UNSET_LONGTABULAR, "unset-longtabular", false },
156         { Tabular::SET_PWIDTH, "set-pwidth", true },
157         { Tabular::SET_MPWIDTH, "set-mpwidth", true },
158         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular", true },
159         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular", true },
160         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular", true },
161         { Tabular::SET_ROTATE_CELL, "set-rotate-cell", true },
162         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell", true },
163         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell", true },
164         { Tabular::SET_USEBOX, "set-usebox", true },
165         { Tabular::SET_LTHEAD, "set-lthead", true },
166         { Tabular::UNSET_LTHEAD, "unset-lthead", true },
167         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead", true },
168         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead", true },
169         { Tabular::SET_LTFOOT, "set-ltfoot", true },
170         { Tabular::UNSET_LTFOOT, "unset-ltfoot", true },
171         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot", true },
172         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot", true },
173         { Tabular::SET_LTNEWPAGE, "set-ltnewpage", false },
174         { Tabular::UNSET_LTNEWPAGE, "unset-ltnewpage", false },
175         { Tabular::TOGGLE_LTCAPTION, "toggle-ltcaption", false },
176         { Tabular::SET_LTCAPTION, "set-ltcaption", false },
177         { Tabular::UNSET_LTCAPTION, "unset-ltcaption", false },
178         { Tabular::SET_SPECIAL_COLUMN, "set-special-column", true },
179         { Tabular::SET_SPECIAL_MULTICOLUMN, "set-special-multicolumn", true },
180         { Tabular::SET_BOOKTABS, "set-booktabs", false },
181         { Tabular::UNSET_BOOKTABS, "unset-booktabs", false },
182         { Tabular::SET_TOP_SPACE, "set-top-space", true },
183         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space", true },
184         { Tabular::SET_INTERLINE_SPACE, "set-interline-space", true },
185         { Tabular::SET_BORDER_LINES, "set-border-lines", false },
186         { Tabular::TABULAR_VALIGN_TOP, "tabular-valign-top", false},
187         { Tabular::TABULAR_VALIGN_MIDDLE, "tabular-valign-middle", false},
188         { Tabular::TABULAR_VALIGN_BOTTOM, "tabular-valign-bottom", false},
189         { Tabular::LONGTABULAR_ALIGN_LEFT, "longtabular-align-left", false },
190         { Tabular::LONGTABULAR_ALIGN_CENTER, "longtabular-align-center", false },
191         { Tabular::LONGTABULAR_ALIGN_RIGHT, "longtabular-align-right", false },
192         { Tabular::SET_DECIMAL_POINT, "set-decimal-point", true },
193         { Tabular::SET_TABULAR_WIDTH, "set-tabular-width", true },
194         { Tabular::LAST_ACTION, "", false }
195 };
196
197
198 string const tostr(LyXAlignment const & num)
199 {
200         switch (num) {
201         case LYX_ALIGN_NONE:
202                 return "none";
203         case LYX_ALIGN_BLOCK:
204                 return "block";
205         case LYX_ALIGN_LEFT:
206                 return "left";
207         case LYX_ALIGN_CENTER:
208                 return "center";
209         case LYX_ALIGN_RIGHT:
210                 return "right";
211         case LYX_ALIGN_LAYOUT:
212                 return "layout";
213         case LYX_ALIGN_SPECIAL:
214                 return "special";
215         case LYX_ALIGN_DECIMAL:
216                 return "decimal";
217         }
218         return string();
219 }
220
221
222 string const tostr(Tabular::HAlignment const & num)
223 {
224         switch (num) {
225         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
226                 return "left";
227         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
228                 return "center";
229         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
230                 return "right";
231         }
232         return string();
233 }
234
235
236 string const tostr(Tabular::VAlignment const & num)
237 {
238         switch (num) {
239         case Tabular::LYX_VALIGN_TOP:
240                 return "top";
241         case Tabular::LYX_VALIGN_MIDDLE:
242                 return "middle";
243         case Tabular::LYX_VALIGN_BOTTOM:
244                 return "bottom";
245         }
246         return string();
247 }
248
249
250 string const tostr(Tabular::BoxType const & num)
251 {
252         switch (num) {
253         case Tabular::BOX_NONE:
254                 return "none";
255         case Tabular::BOX_PARBOX:
256                 return "parbox";
257         case Tabular::BOX_MINIPAGE:
258                 return "minipage";
259         }
260         return string();
261 }
262
263
264 // I would have liked a fromstr template a lot better. (Lgb)
265 bool string2type(string const & str, LyXAlignment & num)
266 {
267         if (str == "none")
268                 num = LYX_ALIGN_NONE;
269         else if (str == "block")
270                 num = LYX_ALIGN_BLOCK;
271         else if (str == "left")
272                 num = LYX_ALIGN_LEFT;
273         else if (str == "center")
274                 num = LYX_ALIGN_CENTER;
275         else if (str == "right")
276                 num = LYX_ALIGN_RIGHT;
277         else if (str == "decimal")
278                 num = LYX_ALIGN_DECIMAL;
279         else
280                 return false;
281         return true;
282 }
283
284
285 bool string2type(string const & str, Tabular::HAlignment & num)
286 {
287         if (str == "left")
288                 num = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
289         else if (str == "center" )
290                 num = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
291         else if (str == "right")
292                 num = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
293         else
294                 return false;
295         return true;
296 }
297
298
299 bool string2type(string const & str, Tabular::VAlignment & num)
300 {
301         if (str == "top")
302                 num = Tabular::LYX_VALIGN_TOP;
303         else if (str == "middle" )
304                 num = Tabular::LYX_VALIGN_MIDDLE;
305         else if (str == "bottom")
306                 num = Tabular::LYX_VALIGN_BOTTOM;
307         else
308                 return false;
309         return true;
310 }
311
312
313 bool string2type(string const & str, Tabular::BoxType & num)
314 {
315         if (str == "none")
316                 num = Tabular::BOX_NONE;
317         else if (str == "parbox")
318                 num = Tabular::BOX_PARBOX;
319         else if (str == "minipage")
320                 num = Tabular::BOX_MINIPAGE;
321         else
322                 return false;
323         return true;
324 }
325
326
327 bool string2type(string const & str, bool & num)
328 {
329         if (str == "true")
330                 num = true;
331         else if (str == "false")
332                 num = false;
333         else
334                 return false;
335         return true;
336 }
337
338
339 bool getTokenValue(string const & str, char const * token, string & ret)
340 {
341         ret.erase();
342         size_t token_length = strlen(token);
343         size_t pos = str.find(token);
344
345         if (pos == string::npos || pos + token_length + 1 >= str.length()
346                 || str[pos + token_length] != '=')
347                 return false;
348         pos += token_length + 1;
349         char ch = str[pos];
350         if (ch != '"' && ch != '\'') { // only read till next space
351                 ret += ch;
352                 ch = ' ';
353         }
354         while (pos < str.length() - 1 && str[++pos] != ch)
355                 ret += str[pos];
356
357         return true;
358 }
359
360
361 bool getTokenValue(string const & str, char const * token, docstring & ret)
362 {
363         string tmp;
364         bool const success = getTokenValue(str, token, tmp);
365         ret = from_utf8(tmp);
366         return success;
367 }
368
369
370 bool getTokenValue(string const & str, char const * token, int & num)
371 {
372         string tmp;
373         num = 0;
374         if (!getTokenValue(str, token, tmp))
375                 return false;
376         num = convert<int>(tmp);
377         return true;
378 }
379
380
381 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
382 {
383         string tmp;
384         return getTokenValue(str, token, tmp) && string2type(tmp, num);
385 }
386
387
388 bool getTokenValue(string const & str, char const * token,
389                                    Tabular::HAlignment & num)
390 {
391         string tmp;
392         return getTokenValue(str, token, tmp) && string2type(tmp, num);
393 }
394
395
396 bool getTokenValue(string const & str, char const * token,
397                                    Tabular::VAlignment & num)
398 {
399         string tmp;
400         return getTokenValue(str, token, tmp) && string2type(tmp, num);
401 }
402
403
404 bool getTokenValue(string const & str, char const * token,
405                                    Tabular::BoxType & num)
406 {
407         string tmp;
408         return getTokenValue(str, token, tmp) && string2type(tmp, num);
409 }
410
411
412 bool getTokenValue(string const & str, char const * token, bool & flag)
413 {
414         // set the flag always to false as this should be the default for bools
415         // not in the file-format.
416         flag = false;
417         string tmp;
418         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
419 }
420
421
422 bool getTokenValue(string const & str, char const * token, Length & len)
423 {
424         // set the length to be zero() as default as this it should be if not
425         // in the file format.
426         len = Length();
427         string tmp;
428         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
429 }
430
431
432 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
433 {
434         len = Length();
435         flag = false;
436         string tmp;
437         if (!getTokenValue(str, token, tmp))
438                 return false;
439         if (tmp == "default") {
440                 flag = true;
441                 return  true;
442         }
443         return isValidLength(tmp, &len);
444 }
445
446
447 void l_getline(istream & is, string & str)
448 {
449         str.erase();
450         while (str.empty()) {
451                 getline(is, str);
452                 if (!str.empty() && str[str.length() - 1] == '\r')
453                         str.erase(str.length() - 1);
454         }
455 }
456
457 template <class T>
458 string const write_attribute(string const & name, T const & t)
459 {
460         string const s = tostr(t);
461         return s.empty() ? s : " " + name + "=\"" + s + "\"";
462 }
463
464 template <>
465 string const write_attribute(string const & name, string const & t)
466 {
467         return t.empty() ? t : " " + name + "=\"" + t + "\"";
468 }
469
470
471 template <>
472 string const write_attribute(string const & name, docstring const & t)
473 {
474         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
475 }
476
477
478 template <>
479 string const write_attribute(string const & name, bool const & b)
480 {
481         // we write only true attribute values so we remove a bit of the
482         // file format bloat for tabulars.
483         return b ? write_attribute(name, convert<string>(b)) : string();
484 }
485
486
487 template <>
488 string const write_attribute(string const & name, int const & i)
489 {
490         // we write only true attribute values so we remove a bit of the
491         // file format bloat for tabulars.
492         return i ? write_attribute(name, convert<string>(i)) : string();
493 }
494
495
496 template <>
497 string const write_attribute(string const & name, Tabular::idx_type const & i)
498 {
499         // we write only true attribute values so we remove a bit of the
500         // file format bloat for tabulars.
501         return i ? write_attribute(name, convert<string>(i)) : string();
502 }
503
504
505 template <>
506 string const write_attribute(string const & name, Length const & value)
507 {
508         // we write only the value if we really have one same reson as above.
509         return value.zero() ? string() : write_attribute(name, value.asString());
510 }
511
512 } // namespace
513
514
515 string const featureAsString(Tabular::Feature action)
516 {
517         for (size_t i = 0; i != Tabular::LAST_ACTION; ++i) {
518                 if (tabularFeature[i].action == action)
519                         return tabularFeature[i].feature;
520         }
521         return string();
522 }
523
524
525 DocIterator separatorPos(InsetTableCell * cell, docstring const & align_d)
526 {
527         DocIterator dit = doc_iterator_begin(&(cell->buffer()), cell);
528         for (; dit; dit.forwardChar())
529                 if (dit.inTexted() && dit.depth() == 1
530                         && dit.paragraph().find(align_d, false, false, dit.pos()))
531                         break;
532
533         return dit;
534 }
535
536
537 InsetTableCell splitCell(InsetTableCell & head, docstring const & align_d, bool & hassep)
538 {
539         InsetTableCell tail = InsetTableCell(head);
540         DocIterator const dit = separatorPos(&head, align_d);
541         hassep = dit;
542         if (hassep) {
543                 pit_type const psize = head.paragraphs().front().size();
544                 head.paragraphs().front().eraseChars(dit.pos(), psize, false);
545                 tail.paragraphs().front().eraseChars(0,
546                         dit.pos() < psize ? dit.pos() + 1 : psize, false);
547         }
548
549         return tail;
550 }
551
552
553 /////////////////////////////////////////////////////////////////////
554 //
555 // Tabular
556 //
557 /////////////////////////////////////////////////////////////////////
558
559
560 Tabular::CellData::CellData(Buffer * buf)
561         : cellno(0),
562           width(0),
563           multicolumn(Tabular::CELL_NORMAL),
564           multirow(Tabular::CELL_NORMAL),
565           alignment(LYX_ALIGN_CENTER),
566           valignment(LYX_VALIGN_TOP),
567           decimal_hoffset(0),
568           decimal_width(0),
569           voffset(0),
570           top_line(false),
571           bottom_line(false),
572           left_line(false),
573           right_line(false),
574           usebox(BOX_NONE),
575           rotate(0),
576           inset(new InsetTableCell(buf))
577 {
578         inset->setBuffer(*buf);
579 }
580
581
582 Tabular::CellData::CellData(CellData const & cs)
583         : cellno(cs.cellno),
584           width(cs.width),
585           multicolumn(cs.multicolumn),
586           multirow(cs.multirow),
587           mroffset(cs.mroffset),
588           alignment(cs.alignment),
589           valignment(cs.valignment),
590           decimal_hoffset(cs.decimal_hoffset),
591           decimal_width(cs.decimal_width),
592           voffset(cs.voffset),
593           top_line(cs.top_line),
594           bottom_line(cs.bottom_line),
595           left_line(cs.left_line),
596           right_line(cs.right_line),
597           usebox(cs.usebox),
598           rotate(cs.rotate),
599           align_special(cs.align_special),
600           p_width(cs.p_width),
601           inset(static_cast<InsetTableCell *>(cs.inset->clone()))
602 {
603 }
604
605 Tabular::CellData & Tabular::CellData::operator=(CellData const & cs)
606 {
607         if (&cs == this)
608                 return *this;
609         cellno = cs.cellno;
610         width = cs.width;
611         multicolumn = cs.multicolumn;
612         multirow = cs.multirow;
613         mroffset = cs.mroffset;
614         alignment = cs.alignment;
615         valignment = cs.valignment;
616         decimal_hoffset = cs.decimal_hoffset;
617         decimal_width = cs.decimal_width;
618         voffset = cs.voffset;
619         top_line = cs.top_line;
620         bottom_line = cs.bottom_line;
621         left_line = cs.left_line;
622         right_line = cs.right_line;
623         usebox = cs.usebox;
624         rotate = cs.rotate;
625         align_special = cs.align_special;
626         p_width = cs.p_width;
627         inset.reset(static_cast<InsetTableCell *>(cs.inset->clone()));
628         return *this;
629 }
630
631 Tabular::RowData::RowData()
632         : ascent(0),
633           descent(0),
634           top_space_default(false),
635           bottom_space_default(false),
636           interline_space_default(false),
637           endhead(false),
638           endfirsthead(false),
639           endfoot(false),
640           endlastfoot(false),
641           newpage(false),
642           caption(false)
643 {}
644
645
646 Tabular::ColumnData::ColumnData()
647         : alignment(LYX_ALIGN_CENTER),
648           valignment(LYX_VALIGN_TOP),
649           width(0)
650 {
651 }
652
653
654 Tabular::ltType::ltType()
655         : set(false), topDL(false),
656           bottomDL(false),
657           empty(false)
658 {}
659
660
661 Tabular::Tabular(Buffer * buffer, row_type rows_arg, col_type columns_arg)
662 {
663         init(buffer, rows_arg, columns_arg);
664 }
665
666
667 void Tabular::setBuffer(Buffer & buffer)
668 {
669         buffer_ = &buffer;
670         for (row_type i = 0; i < nrows(); ++i)
671                 for (col_type j = 0; j < ncols(); ++j)
672                         cell_info[i][j].inset->setBuffer(*buffer_);
673 }
674
675
676 // activates all lines and sets all widths to 0
677 void Tabular::init(Buffer * buf, row_type rows_arg,
678                       col_type columns_arg)
679 {
680         buffer_ = buf;
681         row_info = row_vector(rows_arg);
682         column_info = column_vector(columns_arg);
683         cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf)));
684         row_info.reserve(10);
685         column_info.reserve(10);
686         cell_info.reserve(100);
687         updateIndexes();
688         is_long_tabular = false;
689         tabular_valignment = LYX_VALIGN_MIDDLE;
690         tabular_width = Length();
691         longtabular_alignment = LYX_LONGTABULAR_ALIGN_CENTER;
692         rotate = 0;
693         use_booktabs = false;
694         // set silly default lines
695         for (row_type r = 0; r < nrows(); ++r)
696                 for (col_type c = 0; c < ncols(); ++c) {
697                         cell_info[r][c].inset->setBuffer(*buffer_);
698                         cell_info[r][c].top_line = true;
699                         cell_info[r][c].left_line = true;
700                         cell_info[r][c].bottom_line = r == 0 || r == nrows() - 1;
701                         cell_info[r][c].right_line = c == ncols() - 1;
702                 }
703 }
704
705
706 void Tabular::deleteRow(row_type const row)
707 {
708         // Not allowed to delete last row
709         if (nrows() == 1)
710                 return;
711
712         for (col_type c = 0; c < ncols(); ++c) {
713                 // Care about multirow cells
714                 if (row + 1 < nrows() &&
715                     cell_info[row][c].multirow == CELL_BEGIN_OF_MULTIROW &&
716                     cell_info[row + 1][c].multirow == CELL_PART_OF_MULTIROW) {
717                                 cell_info[row + 1][c].multirow = CELL_BEGIN_OF_MULTIROW;
718                 }
719         }
720         row_info.erase(row_info.begin() + row);
721         cell_info.erase(cell_info.begin() + row);
722         updateIndexes();
723 }
724
725
726 void Tabular::copyRow(row_type const row)
727 {
728         insertRow(row, true);
729 }
730
731
732 void Tabular::appendRow(row_type row)
733 {
734         insertRow(row, false);
735 }
736
737
738 void Tabular::insertRow(row_type const row, bool copy)
739 {
740         row_info.insert(row_info.begin() + row + 1, RowData(row_info[row]));
741         cell_info.insert(cell_info.begin() + row + 1,
742                 cell_vector(0, CellData(buffer_)));
743
744         for (col_type c = 0; c < ncols(); ++c) {
745                 cell_info[row + 1].insert(cell_info[row + 1].begin() + c,
746                         copy ? CellData(cell_info[row][c]) : CellData(buffer_));
747                 if (buffer().params().track_changes)
748                         cell_info[row + 1][c].inset->setChange(Change(Change::INSERTED));
749                 if (cell_info[row][c].multirow == CELL_BEGIN_OF_MULTIROW)
750                         cell_info[row + 1][c].multirow = CELL_PART_OF_MULTIROW;
751         }
752
753         updateIndexes();
754         for (col_type c = 0; c < ncols(); ++c) {
755                 if (isPartOfMultiRow(row, c))
756                         continue;
757                 // inherit line settings
758                 idx_type const i = cellIndex(row + 1, c);
759                 idx_type const j = cellIndex(row, c);
760                 setLeftLine(i, leftLine(j));
761                 setRightLine(i, rightLine(j));
762                 setTopLine(i, topLine(j));
763                 if (topLine(j) && bottomLine(j)) {
764                         setBottomLine(i, true);
765                         setBottomLine(j, false);
766                 }
767                 // mark track changes
768                 if (buffer().params().track_changes)
769                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
770         }
771 }
772
773
774 void Tabular::moveColumn(col_type col, ColDirection direction)
775 {
776         if (direction == Tabular::LEFT)
777                 col = col - 1;
778
779         std::swap(column_info[col], column_info[col + 1]);
780
781         for (row_type r = 0; r < nrows(); ++r) {
782                 std::swap(cell_info[r][col], cell_info[r][col + 1]);
783                 std::swap(cell_info[r][col].left_line, cell_info[r][col + 1].left_line);
784                 std::swap(cell_info[r][col].right_line, cell_info[r][col + 1].right_line);
785
786                 // FIXME track changes is broken for tabular features (#8469)
787                 idx_type const i = cellIndex(r, col);
788                 idx_type const j = cellIndex(r, col + 1);
789                 if (buffer().params().track_changes) {
790                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
791                         cellInfo(j).inset->setChange(Change(Change::INSERTED));
792                 }
793         }
794         updateIndexes();
795 }
796
797
798 void Tabular::moveRow(row_type row, RowDirection direction)
799 {
800         if (direction == Tabular::UP)
801                 row = row - 1;
802
803         std::swap(row_info[row], row_info[row + 1]);
804
805         for (col_type c = 0; c < ncols(); ++c) {
806                 std::swap(cell_info[row][c], cell_info[row + 1][c]);
807                 std::swap(cell_info[row][c].top_line, cell_info[row + 1][c].top_line);
808                 std::swap(cell_info[row][c].bottom_line, cell_info[row + 1][c].bottom_line);
809
810                 // FIXME track changes is broken for tabular features (#8469)
811                 idx_type const i = cellIndex(row, c);
812                 idx_type const j = cellIndex(row + 1, c);
813                 if (buffer().params().track_changes) {
814                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
815                         cellInfo(j).inset->setChange(Change(Change::INSERTED));
816                 }
817         }
818         updateIndexes();
819 }
820
821
822 void Tabular::deleteColumn(col_type const col)
823 {
824         // Not allowed to delete last column
825         if (ncols() == 1)
826                 return;
827
828         for (row_type r = 0; r < nrows(); ++r) {
829                 // Care about multicolumn cells
830                 if (col + 1 < ncols() &&
831                     cell_info[r][col].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
832                     cell_info[r][col + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
833                                 cell_info[r][col + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
834                 }
835                 cell_info[r].erase(cell_info[r].begin() + col);
836         }
837         column_info.erase(column_info.begin() + col);
838         updateIndexes();
839 }
840
841
842 void Tabular::copyColumn(col_type const col)
843 {
844         insertColumn(col, true);
845 }
846
847
848 void Tabular::appendColumn(col_type col)
849 {
850         insertColumn(col, false);
851 }
852
853
854 void Tabular::insertColumn(col_type const col, bool copy)
855 {
856         BufferParams const & bp = buffer().params();
857         column_info.insert(column_info.begin() + col + 1, ColumnData(column_info[col]));
858
859         for (row_type r = 0; r < nrows(); ++r) {
860                 cell_info[r].insert(cell_info[r].begin() + col + 1,
861                         copy ? CellData(cell_info[r][col]) : CellData(buffer_));
862                 if (bp.track_changes)
863                         cell_info[r][col + 1].inset->setChange(Change(Change::INSERTED));
864                 if (cell_info[r][col].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
865                         cell_info[r][col + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
866         }
867         updateIndexes();
868         for (row_type r = 0; r < nrows(); ++r) {
869                 // inherit line settings
870                 idx_type const i = cellIndex(r, col + 1);
871                 idx_type const j = cellIndex(r, col);
872                 setBottomLine(i, bottomLine(j));
873                 setTopLine(i, topLine(j));
874                 setLeftLine(i, leftLine(j));
875                 if (rightLine(i) && rightLine(j)) {
876                         setRightLine(i, true);
877                         setRightLine(j, false);
878                 }
879                 if (buffer().params().track_changes)
880                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
881         }
882 }
883
884
885 void Tabular::updateIndexes()
886 {
887         setBuffer(buffer());
888         numberofcells = 0;
889         // reset cell number
890         for (row_type row = 0; row < nrows(); ++row)
891                 for (col_type column = 0; column < ncols(); ++column) {
892                         if (!isPartOfMultiColumn(row, column)
893                                 && !isPartOfMultiRow(row, column))
894                                 ++numberofcells;
895                         if (isPartOfMultiRow(row, column))
896                                 cell_info[row][column].cellno = cell_info[row - 1][column].cellno;
897                         else
898                                 cell_info[row][column].cellno = numberofcells - 1;
899                 }
900
901         rowofcell.resize(numberofcells);
902         columnofcell.resize(numberofcells);
903         idx_type i = 0;
904         // reset column and row of cells and update their width and alignment
905         for (row_type row = 0; row < nrows(); ++row)
906                 for (col_type column = 0; column < ncols(); ++column) {
907                         if (isPartOfMultiColumn(row, column))
908                                 continue;
909                         // columnofcell needs to be called before setting width and aligment
910                         // multirow cells inherit the width from the column width
911                         if (!isPartOfMultiRow(row, column)) {
912                                 columnofcell[i] = column;
913                                 rowofcell[i] = row;
914                         }
915                         setFixedWidth(row, column);
916                         if (isPartOfMultiRow(row, column))
917                                 continue;
918                         cell_info[row][column].inset->setContentAlignment(
919                                 getAlignment(cellIndex(row, column)));
920                         ++i;
921                 }
922 }
923
924
925 Tabular::idx_type Tabular::numberOfCellsInRow(row_type const row) const
926 {
927         idx_type result = 0;
928         for (col_type c = 0; c < ncols(); ++c)
929                 if (cell_info[row][c].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
930                         ++result;
931         return result;
932 }
933
934
935 bool Tabular::topLine(idx_type const cell) const
936 {
937         return cellInfo(cell).top_line;
938 }
939
940
941 bool Tabular::bottomLine(idx_type const cell) const
942 {
943         return cellInfo(cell).bottom_line;
944 }
945
946
947 bool Tabular::leftLine(idx_type cell) const
948 {
949         if (use_booktabs)
950                 return false;
951         return cellInfo(cell).left_line;
952 }
953
954
955 bool Tabular::rightLine(idx_type cell) const
956 {
957         if (use_booktabs)
958                 return false;
959         return cellInfo(cell).right_line;
960 }
961
962
963 int Tabular::interRowSpace(row_type row) const
964 {
965         if (!row || row >= nrows())
966                 return 0;
967
968         int const interline_space = row_info[row - 1].interline_space_default ?
969                 default_line_space :
970                 row_info[row - 1].interline_space.inPixels(width());
971         if (rowTopLine(row) && rowBottomLine(row - 1))
972                 return interline_space + WIDTH_OF_LINE;
973         return interline_space;
974 }
975
976
977 int Tabular::interColumnSpace(idx_type cell) const
978 {
979         col_type const nextcol = cellColumn(cell) + columnSpan(cell);
980         if (rightLine(cell) && nextcol < ncols()
981                 && leftLine(cellIndex(cellRow(cell), nextcol)))
982                 return WIDTH_OF_LINE;
983         return 0;
984 }
985
986
987 int Tabular::cellWidth(idx_type cell) const
988 {
989         int w = 0;
990         col_type const span = columnSpan(cell);
991         col_type const col = cellColumn(cell);
992         for(col_type c = col; c < col + span ; ++c)
993                 w += column_info[c].width;
994         return w;
995 }
996
997
998 int Tabular::cellHeight(idx_type cell) const
999 {
1000         row_type const span = rowSpan(cell);
1001         row_type const row = cellRow(cell);
1002         int h = 0;
1003         for(row_type r = row; r < row + span ; ++r) {
1004                 h += rowAscent(r) + rowDescent(r);
1005                 if (r != row + span - 1)
1006                         h += interRowSpace(r + 1);
1007         }
1008
1009         return h;
1010 }
1011
1012
1013 bool Tabular::updateColumnWidths()
1014 {
1015         vector<int> max_dwidth(ncols(), 0);
1016         for(col_type c = 0; c < ncols(); ++c)
1017                 for(row_type r = 0; r < nrows(); ++r) {
1018                         idx_type const i = cellIndex(r, c);
1019                         if (getAlignment(i) == LYX_ALIGN_DECIMAL)
1020                                 max_dwidth[c] = max(max_dwidth[c], cell_info[r][c].decimal_width);
1021                 }
1022
1023         bool update = false;
1024         // for each col get max of single col cells
1025         for(col_type c = 0; c < ncols(); ++c) {
1026                 int new_width = 0;
1027                 for(row_type r = 0; r < nrows(); ++r) {
1028                         idx_type const i = cellIndex(r, c);
1029                         if (columnSpan(i) == 1) {
1030                                 if (getAlignment(i) == LYX_ALIGN_DECIMAL
1031                                         && cell_info[r][c].decimal_width!=0)
1032                                         new_width = max(new_width, cellInfo(i).width
1033                                                 + max_dwidth[c] - cellInfo(i).decimal_width);
1034                                 else
1035                                         new_width = max(new_width, cellInfo(i).width);
1036                         }
1037                 }
1038
1039                 if (column_info[c].width != new_width) {
1040                         column_info[c].width = new_width;
1041                         update = true;
1042                 }
1043         }
1044         // update col widths to fit merged cells
1045         for(col_type c = 0; c < ncols(); ++c)
1046                 for(row_type r = 0; r < nrows(); ++r) {
1047                         idx_type const i = cellIndex(r, c);
1048                         int const span = columnSpan(i);
1049                         if (span == 1 || c > cellColumn(i))
1050                                 continue;
1051
1052                         int old_width = 0;
1053                         for(col_type j = c; j < c + span ; ++j)
1054                                 old_width += column_info[j].width;
1055
1056                         if (cellInfo(i).width > old_width) {
1057                                 column_info[c + span - 1].width += cellInfo(i).width - old_width;
1058                                 update = true;
1059                         }
1060                 }
1061
1062         return update;
1063 }
1064
1065
1066 int Tabular::width() const
1067 {
1068         int width = 0;
1069         for (col_type c = 0; c < ncols(); ++c)
1070                 width += column_info[c].width;
1071         return width;
1072 }
1073
1074
1075 void Tabular::setAlignment(idx_type cell, LyXAlignment align,
1076                               bool has_width)
1077 {
1078         col_type const col = cellColumn(cell);
1079         // set alignment for the whole row if we are not in a multicolumn cell,
1080         // exclude possible multicolumn cells in the row
1081         if (!isMultiColumn(cell)) {
1082                 for (row_type r = 0; r < nrows(); ++r) {
1083                         // only if the column has no width the multirow inherits the
1084                         // alignment of the column, otherwise it is left aligned
1085                         if (!(isMultiRow(cellIndex(r, col)) && has_width)
1086                                 && !isMultiColumn(cellIndex(r, col))) {
1087                                 cell_info[r][col].alignment = align;
1088                                 cell_info[r][col].inset->setContentAlignment(align);
1089                         }
1090                         if ((isMultiRow(cellIndex(r, col)) && has_width)
1091                                 && !isMultiColumn(cellIndex(r, col))) {
1092                                 cell_info[r][col].alignment = LYX_ALIGN_LEFT;
1093                                 cell_info[r][col].inset->setContentAlignment(LYX_ALIGN_LEFT);
1094                         }
1095                 }
1096                 column_info[col].alignment = align;
1097                 docstring & dpoint = column_info[col].decimal_point;
1098                 if (align == LYX_ALIGN_DECIMAL && dpoint.empty())
1099                         dpoint = from_utf8(lyxrc.default_decimal_point);
1100         } else {
1101                 cellInfo(cell).alignment = align;
1102                 cellInset(cell).get()->setContentAlignment(align);
1103         }
1104 }
1105
1106
1107 void Tabular::setVAlignment(idx_type cell, VAlignment align,
1108                                bool onlycolumn)
1109 {
1110         if (!isMultiColumn(cell) || onlycolumn)
1111                 column_info[cellColumn(cell)].valignment = align;
1112         if (!onlycolumn)
1113                 cellInfo(cell).valignment = align;
1114 }
1115
1116
1117 namespace {
1118
1119 /**
1120  * Allow line and paragraph breaks for fixed width cells or disallow them,
1121  * merge cell paragraphs and reset layout to standard for variable width
1122  * cells.
1123  */
1124 void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
1125 {
1126         inset->toggleFixedWidth(fixedWidth);
1127         if (fixedWidth)
1128                 return;
1129
1130         // merge all paragraphs to one
1131         BufferParams const & bp = cur.bv().buffer().params();
1132         while (inset->paragraphs().size() > 1)
1133                 mergeParagraph(bp, inset->paragraphs(), 0);
1134
1135         // reset layout
1136         cur.push(*inset);
1137         // undo information has already been recorded
1138         inset->getText(0)->setLayout(0, cur.lastpit() + 1,
1139                         bp.documentClass().plainLayoutName());
1140         cur.pop();
1141 }
1142
1143 }
1144
1145
1146 void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
1147                 Length const & width)
1148 {
1149         col_type const c = cellColumn(cell);
1150
1151         column_info[c].p_width = width;
1152         // reset the vertical alignment to top if the fixed width
1153         // is removed or zero because only fixed width columns can
1154         // have a vertical alignment
1155         if (column_info[c].p_width.zero())
1156                 column_info[c].valignment = LYX_VALIGN_TOP;
1157         for (row_type r = 0; r < nrows(); ++r) {
1158                 idx_type const cell = cellIndex(r, c);
1159                 // because of multicolumns
1160                 toggleFixedWidth(cur, cellInset(cell).get(),
1161                                  !getPWidth(cell).zero());
1162                 if (isMultiRow(cell))
1163                         setAlignment(cell, LYX_ALIGN_LEFT, false);
1164         }
1165         // cur paragraph can become invalid after paragraphs were merged
1166         if (cur.pit() > cur.lastpit())
1167                 cur.pit() = cur.lastpit();
1168         // cur position can become invalid after newlines were removed
1169         if (cur.pos() > cur.lastpos())
1170                 cur.pos() = cur.lastpos();
1171 }
1172
1173
1174 bool Tabular::setFixedWidth(row_type r, col_type c)
1175 {
1176         bool const multicol = cell_info[r][c].multicolumn != CELL_NORMAL;
1177         bool const fixed_width = (!column_info[c].p_width.zero() && !multicol)
1178               || (multicol && !cell_info[r][c].p_width.zero());
1179         cell_info[r][c].inset->toggleFixedWidth(fixed_width);
1180         return fixed_width;
1181 }
1182
1183
1184 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
1185                 Length const & width)
1186 {
1187         if (!isMultiColumn(cell))
1188                 return false;
1189
1190         cellInfo(cell).p_width = width;
1191         toggleFixedWidth(cur, cellInset(cell).get(), !width.zero());
1192         // cur paragraph can become invalid after paragraphs were merged
1193         if (cur.pit() > cur.lastpit())
1194                 cur.pit() = cur.lastpit();
1195         // cur position can become invalid after newlines were removed
1196         if (cur.pos() > cur.lastpos())
1197                 cur.pos() = cur.lastpos();
1198         return true;
1199 }
1200
1201
1202 bool Tabular::setMROffset(Cursor &, idx_type cell, Length const & mroffset)
1203 {
1204         cellInfo(cell).mroffset = mroffset;
1205         return true;
1206 }
1207
1208
1209 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
1210                                  Tabular::Feature what)
1211 {
1212         if (what == SET_SPECIAL_MULTICOLUMN)
1213                 cellInfo(cell).align_special = special;
1214         else
1215                 column_info[cellColumn(cell)].align_special = special;
1216 }
1217
1218
1219 void Tabular::setTopLine(idx_type i, bool line)
1220 {
1221         cellInfo(i).top_line = line;
1222 }
1223
1224
1225 void Tabular::setBottomLine(idx_type i, bool line)
1226 {
1227         cellInfo(i).bottom_line = line;
1228 }
1229
1230
1231 void Tabular::setLeftLine(idx_type cell, bool line)
1232 {
1233         cellInfo(cell).left_line = line;
1234 }
1235
1236
1237 void Tabular::setRightLine(idx_type cell, bool line)
1238 {
1239         cellInfo(cell).right_line = line;
1240 }
1241
1242 bool Tabular::rowTopLine(row_type r) const
1243 {
1244         bool all_rows_set = true;
1245         for (col_type c = 0; all_rows_set && c < ncols(); ++c)
1246                 all_rows_set = cellInfo(cellIndex(r, c)).top_line;
1247         return all_rows_set;
1248 }
1249
1250
1251 bool Tabular::rowBottomLine(row_type r) const
1252 {
1253         bool all_rows_set = true;
1254         for (col_type c = 0; all_rows_set && c < ncols(); ++c)
1255                 all_rows_set = cellInfo(cellIndex(r, c)).bottom_line;
1256         return all_rows_set;
1257 }
1258
1259
1260 bool Tabular::columnLeftLine(col_type c) const
1261 {
1262         if (use_booktabs)
1263                 return false;
1264
1265         int nrows_left = 0;
1266         int total = 0;
1267         for (row_type r = 0; r < nrows(); ++r) {
1268                 idx_type const i = cellIndex(r, c);
1269                 if (c == cellColumn(i)) {
1270                         ++total;
1271                         bool right = c > 0 && cellInfo(cellIndex(r, c - 1)).right_line;
1272                         if (cellInfo(i).left_line || right)
1273                                 ++nrows_left;
1274                 }
1275         }
1276         return 2 * nrows_left >= total;
1277 }
1278
1279
1280 bool Tabular::columnRightLine(col_type c) const
1281 {
1282         if (use_booktabs)
1283                 return false;
1284
1285         int nrows_right = 0;
1286         int total = 0;
1287         for (row_type r = 0; r < nrows(); ++r) {
1288                 idx_type i = cellIndex(r, c);
1289                 if (c == cellColumn(i) + columnSpan(i) - 1) {
1290                         ++total;
1291                         bool left = (c + 1 < ncols()
1292                                 && cellInfo(cellIndex(r, c + 1)).left_line)
1293                                 || c + 1 == ncols();
1294                         if (cellInfo(i).right_line && left)
1295                                 ++nrows_right;
1296                 }
1297         }
1298         return 2 * nrows_right >= total;
1299 }
1300
1301
1302 LyXAlignment Tabular::getAlignment(idx_type cell, bool onlycolumn) const
1303 {
1304         if (!onlycolumn && (isMultiColumn(cell) || isMultiRow(cell)))
1305                 return cellInfo(cell).alignment;
1306
1307         return column_info[cellColumn(cell)].alignment;
1308 }
1309
1310
1311 Tabular::VAlignment
1312 Tabular::getVAlignment(idx_type cell, bool onlycolumn) const
1313 {
1314         if (!onlycolumn && (isMultiColumn(cell) || isMultiRow(cell)))
1315                 return cellInfo(cell).valignment;
1316         return column_info[cellColumn(cell)].valignment;
1317 }
1318
1319
1320 Length const Tabular::getPWidth(idx_type cell) const
1321 {
1322         if (isMultiColumn(cell))
1323                 return cellInfo(cell).p_width;
1324         return column_info[cellColumn(cell)].p_width;
1325 }
1326
1327
1328 Length const Tabular::getMROffset(idx_type cell) const
1329 {
1330         return cellInfo(cell).mroffset;
1331 }
1332
1333
1334 int Tabular::textHOffset(idx_type cell) const
1335 {
1336         // the LaTeX Way :-(
1337         int x = WIDTH_OF_LINE;
1338
1339         int const w = cellWidth(cell) - cellInfo(cell).width;
1340
1341         switch (getAlignment(cell)) {
1342         case LYX_ALIGN_CENTER:
1343                 x += w / 2;
1344                 break;
1345         case LYX_ALIGN_RIGHT:
1346                 x += w;
1347                 break;
1348         case LYX_ALIGN_DECIMAL: {
1349                 // we center when no decimal point
1350                 if (cellInfo(cell).decimal_width == 0) {
1351                         x += w / 2;
1352                         break;
1353                 }
1354                 col_type const c = cellColumn(cell);
1355                 int max_dhoffset = 0;
1356                 for(row_type r = 0; r < row_info.size() ; ++r) {
1357                         idx_type const i = cellIndex(r, c);
1358                         if (getAlignment(i) == LYX_ALIGN_DECIMAL
1359                                 && cellInfo(i).decimal_width != 0)
1360                                 max_dhoffset = max(max_dhoffset, cellInfo(i).decimal_hoffset);
1361                 }
1362                 x += max_dhoffset - cellInfo(cell).decimal_hoffset;
1363         }
1364         default:
1365                 // LYX_ALIGN_LEFT: nothing :-)
1366                 break;
1367         }
1368
1369         return x;
1370 }
1371
1372
1373 int Tabular::textVOffset(idx_type cell) const
1374 {
1375         int voffset = cellInfo(cell).voffset;
1376         if (isMultiRow(cell)) {
1377                 row_type const row = cellRow(cell);
1378                 voffset += (cellHeight(cell) - rowAscent(row) - rowDescent(row))/2;
1379         }
1380         return voffset;
1381 }
1382
1383
1384 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
1385 {
1386         col_type c = 0;
1387         idx_type const numcells = numberOfCellsInRow(row);
1388         // we check against numcells to make sure we do not crash if all the
1389         // cells are multirow (bug #7535), but in that case our return value
1390         // is really invalid, i.e., it is NOT the first cell in the row. but
1391         // i do not know what to do here. (rgh)
1392         while (c < numcells - 1
1393                && cell_info[row][c].multirow == CELL_PART_OF_MULTIROW)
1394                 ++c;
1395         return cell_info[row][c].cellno;
1396 }
1397
1398
1399 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
1400 {
1401         col_type c = ncols() - 1;
1402         // of course we check against 0 so we don't crash. but we have the same
1403         // problem as in the previous routine: if all the cells are part of a
1404         // multirow or part of a multi column, then our return value is invalid.
1405         while (c > 0
1406                && (cell_info[row][c].multirow == CELL_PART_OF_MULTIROW
1407                    || cell_info[row][c].multicolumn == CELL_PART_OF_MULTICOLUMN))
1408                 --c;
1409         return cell_info[row][c].cellno;
1410 }
1411
1412
1413 Tabular::row_type Tabular::cellRow(idx_type cell) const
1414 {
1415         if (cell >= numberofcells)
1416                 return nrows() - 1;
1417         if (cell == npos)
1418                 return 0;
1419         return rowofcell[cell];
1420 }
1421
1422
1423 Tabular::col_type Tabular::cellColumn(idx_type cell) const
1424 {
1425         if (cell >= numberofcells)
1426                 return ncols() - 1;
1427         if (cell == npos)
1428                 return 0;
1429         return columnofcell[cell];
1430 }
1431
1432
1433 void Tabular::write(ostream & os) const
1434 {
1435         // header line
1436         os << "<lyxtabular"
1437            << write_attribute("version", 3)
1438            << write_attribute("rows", nrows())
1439            << write_attribute("columns", ncols())
1440            << ">\n";
1441         // global longtable options
1442         os << "<features"
1443            << write_attribute("rotate", rotate)
1444            << write_attribute("booktabs", use_booktabs)
1445            << write_attribute("islongtable", is_long_tabular)
1446            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1447            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1448            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1449            << write_attribute("headTopDL", endhead.topDL)
1450            << write_attribute("headBottomDL", endhead.bottomDL)
1451            << write_attribute("footTopDL", endfoot.topDL)
1452            << write_attribute("footBottomDL", endfoot.bottomDL)
1453            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1454            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1455            << write_attribute("lastFootEmpty", endlastfoot.empty);
1456         // longtables cannot be aligned vertically
1457         if (!is_long_tabular) {
1458                 os << write_attribute("tabularvalignment", tabular_valignment);
1459                 os << write_attribute("tabularwidth", tabular_width);
1460         }
1461         if (is_long_tabular)
1462                 os << write_attribute("longtabularalignment", longtabular_alignment);
1463         os << ">\n";
1464         for (col_type c = 0; c < ncols(); ++c) {
1465                 os << "<column"
1466                    << write_attribute("alignment", column_info[c].alignment);
1467                 if (column_info[c].alignment == LYX_ALIGN_DECIMAL)
1468                    os << write_attribute("decimal_point", column_info[c].decimal_point);
1469                 os << write_attribute("valignment", column_info[c].valignment)
1470                    << write_attribute("width", column_info[c].p_width.asString())
1471                    << write_attribute("special", column_info[c].align_special)
1472                    << ">\n";
1473         }
1474         for (row_type r = 0; r < nrows(); ++r) {
1475                 static const string def("default");
1476                 os << "<row";
1477                 if (row_info[r].top_space_default)
1478                         os << write_attribute("topspace", def);
1479                 else
1480                         os << write_attribute("topspace", row_info[r].top_space);
1481                 if (row_info[r].bottom_space_default)
1482                         os << write_attribute("bottomspace", def);
1483                 else
1484                         os << write_attribute("bottomspace", row_info[r].bottom_space);
1485                 if (row_info[r].interline_space_default)
1486                         os << write_attribute("interlinespace", def);
1487                 else
1488                         os << write_attribute("interlinespace", row_info[r].interline_space);
1489                 os << write_attribute("endhead", row_info[r].endhead)
1490                    << write_attribute("endfirsthead", row_info[r].endfirsthead)
1491                    << write_attribute("endfoot", row_info[r].endfoot)
1492                    << write_attribute("endlastfoot", row_info[r].endlastfoot)
1493                    << write_attribute("newpage", row_info[r].newpage)
1494                    << write_attribute("caption", row_info[r].caption)
1495                    << ">\n";
1496                 for (col_type c = 0; c < ncols(); ++c) {
1497                         os << "<cell"
1498                            << write_attribute("multicolumn", cell_info[r][c].multicolumn)
1499                            << write_attribute("multirow", cell_info[r][c].multirow)
1500                            << write_attribute("mroffset", cell_info[r][c].mroffset)
1501                            << write_attribute("alignment", cell_info[r][c].alignment)
1502                            << write_attribute("valignment", cell_info[r][c].valignment)
1503                            << write_attribute("topline", cell_info[r][c].top_line)
1504                            << write_attribute("bottomline", cell_info[r][c].bottom_line)
1505                            << write_attribute("leftline", cell_info[r][c].left_line)
1506                            << write_attribute("rightline", cell_info[r][c].right_line)
1507                            << write_attribute("rotate", cell_info[r][c].rotate)
1508                            << write_attribute("usebox", cell_info[r][c].usebox)
1509                            << write_attribute("width", cell_info[r][c].p_width)
1510                            << write_attribute("special", cell_info[r][c].align_special)
1511                            << ">\n";
1512                         os << "\\begin_inset ";
1513                         cell_info[r][c].inset->write(os);
1514                         os << "\n\\end_inset\n"
1515                            << "</cell>\n";
1516                         // FIXME This can be removed again once the mystery
1517                         // crash has been resolved.
1518                         os << flush;
1519                 }
1520                 os << "</row>\n";
1521         }
1522         os << "</lyxtabular>\n";
1523 }
1524
1525
1526 void Tabular::read(Lexer & lex)
1527 {
1528         string line;
1529         istream & is = lex.getStream();
1530
1531         l_getline(is, line);
1532         if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
1533                 LASSERT(false, return);
1534         }
1535
1536         int version;
1537         if (!getTokenValue(line, "version", version))
1538                 return;
1539         LATTEST(version >= 2);
1540
1541         int rows_arg;
1542         if (!getTokenValue(line, "rows", rows_arg))
1543                 return;
1544         int columns_arg;
1545         if (!getTokenValue(line, "columns", columns_arg))
1546                 return;
1547         init(buffer_, rows_arg, columns_arg);
1548         l_getline(is, line);
1549         if (!prefixIs(line, "<features")) {
1550                 lyxerr << "Wrong tabular format (expected <features ...> got"
1551                        << line << ')' << endl;
1552                 return;
1553         }
1554         getTokenValue(line, "rotate", rotate);
1555         getTokenValue(line, "booktabs", use_booktabs);
1556         getTokenValue(line, "islongtable", is_long_tabular);
1557         getTokenValue(line, "tabularvalignment", tabular_valignment);
1558         getTokenValue(line, "tabularwidth", tabular_width);
1559         getTokenValue(line, "longtabularalignment", longtabular_alignment);
1560         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1561         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1562         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1563         getTokenValue(line, "headTopDL", endhead.topDL);
1564         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1565         getTokenValue(line, "footTopDL", endfoot.topDL);
1566         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1567         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1568         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1569         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1570
1571         for (col_type c = 0; c < ncols(); ++c) {
1572                 l_getline(is,line);
1573                 if (!prefixIs(line,"<column")) {
1574                         lyxerr << "Wrong tabular format (expected <column ...> got"
1575                                << line << ')' << endl;
1576                         return;
1577                 }
1578                 getTokenValue(line, "alignment", column_info[c].alignment);
1579                 getTokenValue(line, "decimal_point", column_info[c].decimal_point);
1580                 getTokenValue(line, "valignment", column_info[c].valignment);
1581                 getTokenValue(line, "width", column_info[c].p_width);
1582                 getTokenValue(line, "special", column_info[c].align_special);
1583         }
1584
1585         for (row_type i = 0; i < nrows(); ++i) {
1586                 l_getline(is, line);
1587                 if (!prefixIs(line, "<row")) {
1588                         lyxerr << "Wrong tabular format (expected <row ...> got"
1589                                << line << ')' << endl;
1590                         return;
1591                 }
1592                 getTokenValue(line, "topspace", row_info[i].top_space,
1593                               row_info[i].top_space_default);
1594                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1595                               row_info[i].bottom_space_default);
1596                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1597                               row_info[i].interline_space_default);
1598                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1599                 getTokenValue(line, "endhead", row_info[i].endhead);
1600                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1601                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1602                 getTokenValue(line, "newpage", row_info[i].newpage);
1603                 getTokenValue(line, "caption", row_info[i].caption);
1604                 for (col_type j = 0; j < ncols(); ++j) {
1605                         l_getline(is, line);
1606                         if (!prefixIs(line, "<cell")) {
1607                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1608                                        << line << ')' << endl;
1609                                 return;
1610                         }
1611                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1612                         getTokenValue(line, "multirow", cell_info[i][j].multirow);
1613                         getTokenValue(line, "mroffset", cell_info[i][j].mroffset);
1614                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1615                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1616                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1617                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1618                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1619                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1620                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1621                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1622                         getTokenValue(line, "width", cell_info[i][j].p_width);
1623                         setFixedWidth(i,j);
1624                         getTokenValue(line, "special", cell_info[i][j].align_special);
1625                         l_getline(is, line);
1626                         if (prefixIs(line, "\\begin_inset")) {
1627                                 cell_info[i][j].inset->setBuffer(*buffer_);
1628                                 cell_info[i][j].inset->read(lex);
1629                                 l_getline(is, line);
1630                         }
1631                         if (!prefixIs(line, "</cell>")) {
1632                                 lyxerr << "Wrong tabular format (expected </cell> got"
1633                                        << line << ')' << endl;
1634                                 return;
1635                         }
1636                 }
1637                 l_getline(is, line);
1638                 if (!prefixIs(line, "</row>")) {
1639                         lyxerr << "Wrong tabular format (expected </row> got"
1640                                << line << ')' << endl;
1641                         return;
1642                 }
1643         }
1644         while (!prefixIs(line, "</lyxtabular>")) {
1645                 l_getline(is, line);
1646         }
1647         updateIndexes();
1648 }
1649
1650
1651 bool Tabular::isMultiColumn(idx_type cell) const
1652 {
1653         return (cellInfo(cell).multicolumn == CELL_BEGIN_OF_MULTICOLUMN
1654                 || cellInfo(cell).multicolumn == CELL_PART_OF_MULTICOLUMN);
1655 }
1656
1657
1658 bool Tabular::hasMultiColumn(col_type c) const
1659 {
1660         for (row_type r = 0; r < nrows(); ++r) {
1661                 if (isMultiColumn(cellIndex(r, c)))
1662                         return true;
1663         }
1664         return false;
1665 }
1666
1667
1668 Tabular::CellData & Tabular::cellInfo(idx_type cell) const
1669 {
1670         return cell_info[cellRow(cell)][cellColumn(cell)];
1671 }
1672
1673
1674 Tabular::idx_type Tabular::setMultiColumn(idx_type cell, idx_type number,
1675                                           bool const right_border)
1676 {
1677         idx_type const col = cellColumn(cell);
1678         idx_type const row = cellRow(cell);
1679         for (idx_type i = 0; i < number; ++i)
1680                 unsetMultiRow(cellIndex(row, col + i));
1681
1682         // unsetting of multirow may have invalidated cell index
1683         cell = cellIndex(row, col);
1684         CellData & cs = cellInfo(cell);
1685         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1686         if (column_info[col].alignment != LYX_ALIGN_DECIMAL)
1687                 cs.alignment = column_info[col].alignment;
1688         setRightLine(cell, right_border);
1689
1690         idx_type lastcell = cellIndex(row, col + number - 1);
1691         for (idx_type i = 1; i < lastcell - cell + 1; ++i) {
1692                 CellData & cs1 = cellInfo(cell + i);
1693                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1694                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1695                 cs1.inset->clear();
1696         }
1697         updateIndexes();
1698         return cell;
1699 }
1700
1701
1702 bool Tabular::isMultiRow(idx_type cell) const
1703 {
1704         return (cellInfo(cell).multirow == CELL_BEGIN_OF_MULTIROW
1705                 || cellInfo(cell).multirow == CELL_PART_OF_MULTIROW);
1706 }
1707
1708 bool Tabular::hasMultiRow(row_type r) const
1709 {
1710         for (col_type c = 0; c < ncols(); ++c) {
1711                 if (isMultiRow(cellIndex(r, c)))
1712                         return true;
1713         }
1714         return false;
1715 }
1716
1717 Tabular::idx_type Tabular::setMultiRow(idx_type cell, idx_type number,
1718                                        bool const bottom_border,
1719                                        LyXAlignment const halign)
1720 {
1721         idx_type const col = cellColumn(cell);
1722         idx_type const row = cellRow(cell);
1723         for (idx_type i = 0; i < number; ++i)
1724                 unsetMultiColumn(cellIndex(row + i, col));
1725
1726         // unsetting of multirow may have invalidated cell index
1727         cell = cellIndex(row, col);
1728         CellData & cs = cellInfo(cell);
1729         cs.multirow = CELL_BEGIN_OF_MULTIROW;
1730         cs.valignment = LYX_VALIGN_MIDDLE;
1731         // the horizontal alignment of multirow cells can only
1732         // be changed for the whole table row,
1733         // support changing this only for the multirow cell can be done via
1734         // \multirowsetup
1735         if (getPWidth(cell).zero())
1736                 cs.alignment = halign;
1737         else
1738                 cs.alignment = LYX_ALIGN_LEFT;
1739
1740         // set the bottom line of the last selected cell
1741         setBottomLine(cell, bottom_border);
1742
1743         for (idx_type i = 1; i < number; ++i) {
1744                 CellData & cs1 = cell_info[row + i][col];
1745                 cs1.multirow = CELL_PART_OF_MULTIROW;
1746                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1747                 cs1.inset->clear();
1748         }
1749         updateIndexes();
1750         return cell;
1751 }
1752
1753
1754 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
1755 {
1756         row_type const row = cellRow(cell);
1757         col_type const col = cellColumn(cell);
1758         int span = 1;
1759         while (col + span < ncols() && isPartOfMultiColumn(row, col + span))
1760                 ++span;
1761
1762         return span;
1763 }
1764
1765
1766 Tabular::idx_type Tabular::rowSpan(idx_type cell) const
1767 {
1768         col_type const column = cellColumn(cell);
1769         col_type row = cellRow(cell) + 1;
1770         while (row < nrows() && isPartOfMultiRow(row, column))
1771                 ++row;
1772
1773         return row - cellRow(cell);
1774 }
1775
1776
1777 void Tabular::unsetMultiColumn(idx_type cell)
1778 {
1779         if (!isMultiColumn(cell))
1780                 return;
1781
1782         row_type const row = cellRow(cell);
1783         col_type const col = cellColumn(cell);
1784         row_type const span = columnSpan(cell);
1785         for (col_type c = 0; c < span; ++c) {
1786                 // in the table dialog the lines are set in every case
1787                 // when unsetting a multicolumn this leads to an additional right
1788                 // line for every cell that was part of the former multicolumn cell,
1789                 // except if the cell is in the last column
1790                 // therefore remove this line
1791                 if (cell_info[row][col + c].multicolumn == CELL_BEGIN_OF_MULTICOLUMN
1792                         && (col + c) < (col + span - 1))
1793                         cell_info[row][col + c].right_line = false;
1794                 cell_info[row][col + c].multicolumn = CELL_NORMAL;
1795         }
1796         updateIndexes();
1797 }
1798
1799
1800 void Tabular::unsetMultiRow(idx_type cell)
1801 {
1802         if (!isMultiRow(cell))
1803                 return;
1804
1805         cellInfo(cell).valignment = LYX_VALIGN_TOP;
1806         cellInfo(cell).alignment = LYX_ALIGN_CENTER;
1807         row_type const row = cellRow(cell);
1808         col_type const col = cellColumn(cell);
1809         row_type const span = rowSpan(cell);
1810         for (row_type r = 0; r < span; ++r)
1811                 cell_info[row + r][col].multirow = CELL_NORMAL;
1812         updateIndexes();
1813 }
1814
1815
1816 void Tabular::setRotateCell(idx_type cell, int value)
1817 {
1818         cellInfo(cell).rotate = value;
1819 }
1820
1821
1822 int Tabular::getRotateCell(idx_type cell) const
1823 {
1824         return cellInfo(cell).rotate;
1825 }
1826
1827
1828 bool Tabular::needRotating() const
1829 {
1830         if (rotate)
1831                 return true;
1832         for (row_type r = 0; r < nrows(); ++r)
1833                 for (col_type c = 0; c < ncols(); ++c)
1834                         if (cell_info[r][c].rotate != 0)
1835                                 return true;
1836         return false;
1837 }
1838
1839
1840 bool Tabular::isLastCell(idx_type cell) const
1841 {
1842         if (cell + 1 < numberofcells)
1843                 return false;
1844         return true;
1845 }
1846
1847
1848 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
1849 {
1850         if (cellRow(cell) == 0)
1851                 return cell;
1852
1853         col_type const col = cellColumn(cell);
1854         row_type r = cellRow(cell) - 1;
1855         while (r > 0 && cell_info[r][col].multirow == CELL_PART_OF_MULTIROW)
1856                 --r;
1857
1858         return cell_info[r][col].cellno;
1859 }
1860
1861
1862 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
1863 {
1864         row_type const nextrow = cellRow(cell) + rowSpan(cell);
1865         if (nextrow < nrows())
1866                 return cell_info[nextrow][cellColumn(cell)].cellno;
1867         return cell;
1868 }
1869
1870
1871 Tabular::idx_type Tabular::cellIndex(row_type row, col_type column) const
1872 {
1873         LASSERT(column != npos && column < ncols(), column = 0);
1874         LASSERT(row != npos && row < nrows(), row = 0);
1875         return cell_info[row][column].cellno;
1876 }
1877
1878
1879 void Tabular::setUsebox(idx_type cell, BoxType type)
1880 {
1881         cellInfo(cell).usebox = type;
1882 }
1883
1884
1885 // FIXME: Remove this routine because we cannot insert \parboxes when the user
1886 // adds line breaks, see bug 4886.
1887 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
1888 {
1889         if ((!column_info[cellColumn(cell)].p_width.zero() && !isMultiColumn(cell)) ||
1890                 (isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
1891                 return BOX_NONE;
1892         if (cellInfo(cell).usebox > 1)
1893                 return cellInfo(cell).usebox;
1894         return useParbox(cell);
1895 }
1896
1897
1898 ///
1899 //  This are functions used for the longtable support
1900 ///
1901 void Tabular::setLTHead(row_type row, bool flag, ltType const & hd,
1902                            bool first)
1903 {
1904         if (first) {
1905                 endfirsthead = hd;
1906                 if (hd.set)
1907                         row_info[row].endfirsthead = flag;
1908         } else {
1909                 endhead = hd;
1910                 if (hd.set)
1911                         row_info[row].endhead = flag;
1912         }
1913 }
1914
1915
1916 bool Tabular::getRowOfLTHead(row_type row, ltType & hd) const
1917 {
1918         hd = endhead;
1919         hd.set = haveLTHead();
1920         return row_info[row].endhead;
1921 }
1922
1923
1924 bool Tabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1925 {
1926         hd = endfirsthead;
1927         hd.set = haveLTFirstHead();
1928         return row_info[row].endfirsthead;
1929 }
1930
1931
1932 void Tabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1933                            bool last)
1934 {
1935         if (last) {
1936                 endlastfoot = fd;
1937                 if (fd.set)
1938                         row_info[row].endlastfoot = flag;
1939         } else {
1940                 endfoot = fd;
1941                 if (fd.set)
1942                         row_info[row].endfoot = flag;
1943         }
1944 }
1945
1946
1947 bool Tabular::getRowOfLTFoot(row_type row, ltType & fd) const
1948 {
1949         fd = endfoot;
1950         fd.set = haveLTFoot();
1951         return row_info[row].endfoot;
1952 }
1953
1954
1955 bool Tabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1956 {
1957         fd = endlastfoot;
1958         fd.set = haveLTLastFoot();
1959         return row_info[row].endlastfoot;
1960 }
1961
1962
1963 void Tabular::setLTNewPage(row_type row, bool what)
1964 {
1965         row_info[row].newpage = what;
1966 }
1967
1968
1969 bool Tabular::getLTNewPage(row_type row) const
1970 {
1971         return row_info[row].newpage;
1972 }
1973
1974
1975 bool Tabular::haveLTHead(bool withcaptions) const
1976 {
1977         if (!is_long_tabular)
1978                 return false;
1979         for (row_type i = 0; i < nrows(); ++i)
1980                 if (row_info[i].endhead &&
1981                     (withcaptions || !row_info[i].caption))
1982                         return true;
1983         return false;
1984 }
1985
1986
1987 bool Tabular::haveLTFirstHead(bool withcaptions) const
1988 {
1989         if (!is_long_tabular || endfirsthead.empty)
1990                 return false;
1991         for (row_type r = 0; r < nrows(); ++r)
1992                 if (row_info[r].endfirsthead &&
1993                     (withcaptions || !row_info[r].caption))
1994                         return true;
1995         return false;
1996 }
1997
1998
1999 bool Tabular::haveLTFoot(bool withcaptions) const
2000 {
2001         if (!is_long_tabular)
2002                 return false;
2003         for (row_type r = 0; r < nrows(); ++r)
2004                 if (row_info[r].endfoot &&
2005                     (withcaptions || !row_info[r].caption))
2006                         return true;
2007         return false;
2008 }
2009
2010
2011 bool Tabular::haveLTLastFoot(bool withcaptions) const
2012 {
2013         if (!is_long_tabular || endlastfoot.empty)
2014                 return false;
2015         for (row_type r = 0; r < nrows(); ++r)
2016                 if (row_info[r].endlastfoot &&
2017                     (withcaptions || !row_info[r].caption))
2018                         return true;
2019         return false;
2020 }
2021
2022
2023 Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
2024 {
2025         idx_type i = getFirstCellInRow(row);
2026         if (what) {
2027                 setMultiColumn(i, numberOfCellsInRow(row), false);
2028                 setTopLine(i, false);
2029                 setBottomLine(i, false);
2030                 setLeftLine(i, false);
2031                 setRightLine(i, false);
2032                 if (!row_info[row].endfirsthead && !row_info[row].endhead &&
2033                     !row_info[row].endfoot && !row_info[row].endlastfoot) {
2034                         setLTHead(row, true, endfirsthead, true);
2035                         row_info[row].endfirsthead = true;
2036                 }
2037         } else {
2038                 unsetMultiColumn(i);
2039                 // When unsetting a caption row, also all existing
2040                 // captions in this row must be dissolved.
2041         }
2042         row_info[row].caption = what;
2043         return i;
2044 }
2045
2046
2047 bool Tabular::ltCaption(row_type row) const
2048 {
2049         return row_info[row].caption;
2050 }
2051
2052
2053 bool Tabular::haveLTCaption(CaptionType captiontype) const
2054 {
2055         if (!is_long_tabular)
2056                 return false;
2057         for (row_type r = 0; r < nrows(); ++r) {
2058                 if (row_info[r].caption) {
2059                         switch (captiontype) {
2060                         case CAPTION_FIRSTHEAD:
2061                                 if (row_info[r].endfirsthead)
2062                                         return true;
2063                                 break;
2064                         case CAPTION_HEAD:
2065                                 if (row_info[r].endhead)
2066                                         return true;
2067                                 break;
2068                         case CAPTION_FOOT:
2069                                 if (row_info[r].endfoot)
2070                                         return true;
2071                                 break;
2072                         case CAPTION_LASTFOOT:
2073                                 if (row_info[r].endlastfoot)
2074                                         return true;
2075                                 break;
2076                         case CAPTION_ANY:
2077                                 return true;
2078                         }
2079                 }
2080         }
2081         return false;
2082 }
2083
2084
2085 // end longtable support functions
2086
2087 void Tabular::setRowAscent(row_type row, int height)
2088 {
2089         if (row >= nrows() || row_info[row].ascent == height)
2090                 return;
2091         row_info[row].ascent = height;
2092 }
2093
2094
2095 void Tabular::setRowDescent(row_type row, int height)
2096 {
2097         if (row >= nrows() || row_info[row].descent == height)
2098                 return;
2099         row_info[row].descent = height;
2100 }
2101
2102
2103 int Tabular::rowAscent(row_type row) const
2104 {
2105         LASSERT(row < nrows(), row = 0);
2106         return row_info[row].ascent;
2107 }
2108
2109
2110 int Tabular::rowDescent(row_type row) const
2111 {
2112         LASSERT(row < nrows(), row = 0);
2113         return row_info[row].descent;
2114 }
2115
2116
2117 int Tabular::height() const
2118 {
2119         int height = 0;
2120         for (row_type row = 0; row < nrows(); ++row)
2121                 height += rowAscent(row) + rowDescent(row) +
2122                         interRowSpace(row);
2123         return height;
2124 }
2125
2126
2127 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
2128 {
2129         LASSERT(row < nrows(), return false);
2130         LASSERT(column < ncols(), return false);
2131         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
2132 }
2133
2134
2135 bool Tabular::isPartOfMultiRow(row_type row, col_type column) const
2136 {
2137         LASSERT(row < nrows(), return false);
2138         LASSERT(column < ncols(), return false);
2139         return cell_info[row][column].multirow == CELL_PART_OF_MULTIROW;
2140 }
2141
2142
2143 void Tabular::TeXTopHLine(otexstream & os, row_type row, string const & lang) const
2144 {
2145         // we only output complete row lines and the 1st row here, the rest
2146         // is done in Tabular::TeXBottomHLine(...)
2147
2148         // get for each column the topline (if any)
2149         vector<bool> topline;
2150         col_type nset = 0;
2151         for (col_type c = 0; c < ncols(); ++c) {
2152                 topline.push_back(topLine(cellIndex(row, c)));
2153                 // If cell is part of a multirow and not the first cell of the
2154                 // multirow, no line must be drawn.
2155                 if (row != 0)
2156                         if (isMultiRow(cellIndex(row, c))
2157                             && cell_info[row][c].multirow != CELL_BEGIN_OF_MULTIROW)
2158                                 topline[c] = false;
2159                 if (topline[c])
2160                         ++nset;
2161         }
2162
2163         // do nothing if empty first row, or incomplete row line after
2164         if ((row == 0 && nset == 0) || (row > 0 && nset != ncols()))
2165                 return;
2166
2167         // only output complete row lines and the 1st row's clines
2168         if (nset == ncols()) {
2169                 if (use_booktabs) {
2170                         os << (row == 0 ? "\\toprule " : "\\midrule ");
2171                 } else {
2172                         os << "\\hline ";
2173                 }
2174         } else if (row == 0) {
2175                 for (col_type c = 0; c < ncols(); ++c) {
2176                         if (topline[c]) {
2177                                 col_type offset = 0;
2178                                 for (col_type j = 0 ; j < c; ++j)
2179                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2180                                                 ++offset;
2181
2182                                 //babel makes the "-" character an active one, so we have to suppress this here
2183                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
2184                                 if (lang == "slovak" || lang == "czech")
2185                                         os << "\\expandafter" << (use_booktabs ? "\\cmidrule" : "\\cline")
2186                                         << "\\expandafter{\\expandafter" << c + 1 + offset << "\\string-";
2187                                 else
2188                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 + offset << '-';
2189
2190                                 col_type cstart = c;
2191                                 for ( ; c < ncols() && topline[c]; ++c) {}
2192
2193                                 for (col_type j = cstart ; j < c ; ++j)
2194                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2195                                                 ++offset;
2196
2197                                 os << c + offset << "} ";
2198                         }
2199                 }
2200         }
2201         os << "\n";
2202 }
2203
2204
2205 void Tabular::TeXBottomHLine(otexstream & os, row_type row, string const & lang) const
2206 {
2207         // we output bottomlines of row r and the toplines of row r+1
2208         // if the latter do not span the whole tabular
2209
2210         // get the bottomlines of row r, and toplines in next row
2211         bool lastrow = row == nrows() - 1;
2212         vector<bool> bottomline, topline;
2213         bool nextrowset = true;
2214         for (col_type c = 0; c < ncols(); ++c) {
2215                 bottomline.push_back(bottomLine(cellIndex(row, c)));
2216                 topline.push_back(!lastrow && topLine(cellIndex(row + 1, c)));
2217                 // If cell is part of a multirow and not the last cell of the
2218                 // multirow, no line must be drawn.
2219                 if (!lastrow)
2220                         if (isMultiRow(cellIndex(row, c))
2221                             && isMultiRow(cellIndex(row + 1, c))
2222                             && cell_info[row + 1][c].multirow != CELL_BEGIN_OF_MULTIROW) {
2223                                 bottomline[c] = false;
2224                                 topline[c] = false;
2225                                 }
2226                 nextrowset &= topline[c];
2227         }
2228
2229         // combine this row's bottom lines and next row's toplines if necessary
2230         col_type nset = 0;
2231         for (col_type c = 0; c < ncols(); ++c) {
2232                 if (!nextrowset)
2233                         bottomline[c] = bottomline[c] || topline[c];
2234                 if (bottomline[c])
2235                         ++nset;
2236         }
2237
2238         // do nothing if empty, OR incomplete row line with a topline in next row
2239         if (nset == 0 || (nextrowset && nset != ncols()))
2240                 return;
2241
2242         if (nset == ncols()) {
2243                 if (use_booktabs)
2244                         os << (lastrow ? "\\bottomrule" : "\\midrule");
2245                 else
2246                         os << "\\hline ";
2247         } else {
2248                 for (col_type c = 0; c < ncols(); ++c) {
2249                         if (bottomline[c]) {
2250                                 col_type offset = 0;
2251                                 for (col_type j = 0 ; j < c; ++j)
2252                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2253                                                 ++offset;
2254
2255                                 //babel makes the "-" character an active one, so we have to suppress this here
2256                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
2257                                 if (lang == "slovak" || lang == "czech")
2258                                         os << "\\expandafter" << (use_booktabs ? "\\cmidrule" : "\\cline")
2259                                         << "\\expandafter{\\expandafter" << c + 1 + offset << "\\string-";
2260                                 else
2261                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 + offset << '-';
2262
2263                                 col_type cstart = c;
2264                                 for ( ; c < ncols() && bottomline[c]; ++c) {}
2265
2266                                 for (col_type j = cstart ; j < c ; ++j)
2267                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2268                                                 ++offset;
2269
2270                                 os << c + offset << "} ";
2271                         }
2272                 }
2273         }
2274         os << "\n";
2275 }
2276
2277
2278 void Tabular::TeXCellPreamble(otexstream & os, idx_type cell,
2279                               bool & ismulticol, bool & ismultirow) const
2280 {
2281         row_type const r = cellRow(cell);
2282         if (is_long_tabular && row_info[r].caption)
2283                 return;
2284
2285         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
2286         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
2287         // figure out how to set the lines
2288         // we always set double lines to the right of the cell
2289         col_type const c = cellColumn(cell);
2290         col_type const nextcol = c + columnSpan(cell);
2291         bool colright = columnRightLine(c);
2292         bool colleft = columnLeftLine(c);
2293         bool nextcolleft = nextcol < ncols() && columnLeftLine(nextcol);
2294         bool nextcellleft = nextcol < ncols()
2295                 && leftLine(cellIndex(r, nextcol));
2296         bool coldouble = colright && nextcolleft;
2297         bool celldouble = rightLine(cell) && nextcellleft;
2298
2299         ismulticol = isMultiColumn(cell)
2300                 || (c == 0 && colleft != leftLine(cell))
2301                 || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
2302                 || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
2303                 || (coldouble != celldouble);
2304
2305         // we center in multicol when no decimal point
2306         if (column_info[c].alignment == LYX_ALIGN_DECIMAL) {
2307                 docstring const align_d = column_info[c].decimal_point;
2308                 DocIterator const dit = separatorPos(cellInset(cell).get(), align_d);
2309                 ismulticol |= !dit;
2310         }
2311
2312         // up counter by 1 for each decimally aligned col since they use 2 latex cols
2313         int latexcolspan = columnSpan(cell);
2314         for(col_type col = c; col < c + columnSpan(cell); ++col)
2315                 if (column_info[col].alignment == LYX_ALIGN_DECIMAL)
2316                         ++latexcolspan;
2317
2318         if (ismulticol) {
2319                 os << "\\multicolumn{" << latexcolspan << "}{";
2320                 if (c ==0 && leftLine(cell))
2321                         os << '|';
2322                 if (!cellInfo(cell).align_special.empty()) {
2323                         os << cellInfo(cell).align_special;
2324                 } else {
2325                         if (!getPWidth(cell).zero()) {
2326                                 switch (align) {
2327                                 case LYX_ALIGN_LEFT:
2328                                         os << ">{\\raggedright}";
2329                                         break;
2330                                 case LYX_ALIGN_RIGHT:
2331                                         os << ">{\\raggedleft}";
2332                                         break;
2333                                 case LYX_ALIGN_CENTER:
2334                                         os << ">{\\centering}";
2335                                         break;
2336                                 default:
2337                                         break;
2338                                 }
2339                                 switch (valign) {
2340                                 case LYX_VALIGN_TOP:
2341                                         os << 'p';
2342                                         break;
2343                                 case LYX_VALIGN_MIDDLE:
2344                                         os << 'm';
2345                                         break;
2346                                 case LYX_VALIGN_BOTTOM:
2347                                         os << 'b';
2348                                         break;
2349                                 }
2350                                 os << '{'
2351                                    << from_ascii(getPWidth(cell).asLatexString())
2352                                    << '}';
2353                         } else {
2354                                 switch (align) {
2355                                 case LYX_ALIGN_LEFT:
2356                                         os << 'l';
2357                                         break;
2358                                 case LYX_ALIGN_RIGHT:
2359                                         os << 'r';
2360                                         break;
2361                                 default:
2362                                         os << 'c';
2363                                         break;
2364                                 }
2365                         } // end if else !getPWidth
2366                 } // end if else !cellinfo_of_cell
2367                 if (rightLine(cell) || nextcellleft)
2368                         os << '|';
2369                 if (celldouble)
2370                         // add extra vertical line if we want a double one
2371                         os << '|';
2372                 os << "}{";
2373         } // end if ismulticol
2374
2375         // we only need code for the first multirow cell
2376         ismultirow = isMultiRow(cell);
2377         if (ismultirow) {
2378                 os << "\\multirow{" << rowSpan(cell) << "}{";
2379                 if (!getPWidth(cell).zero())
2380                         os << from_ascii(getPWidth(cell).asLatexString());
2381                 else
2382                         // we need to set a default value
2383                         os << "*";
2384                 os << "}";
2385                 if (!getMROffset(cell).zero())
2386                         os << "[" << from_ascii(getMROffset(cell).asLatexString()) << "]";
2387                 os << "{";
2388         } // end if ismultirow
2389
2390         if (getRotateCell(cell) != 0)
2391                 os << "\\begin{turn}{" << convert<string>(getRotateCell(cell)) << "}\n";
2392
2393         if (getUsebox(cell) == BOX_PARBOX) {
2394                 os << "\\parbox[";
2395                 switch (valign) {
2396                 case LYX_VALIGN_TOP:
2397                         os << 't';
2398                         break;
2399                 case LYX_VALIGN_MIDDLE:
2400                         os << 'c';
2401                         break;
2402                 case LYX_VALIGN_BOTTOM:
2403                         os << 'b';
2404                         break;
2405                 }
2406                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2407                    << "}{";
2408         } else if (getUsebox(cell) == BOX_MINIPAGE) {
2409                 os << "\\begin{minipage}[";
2410                 switch (valign) {
2411                 case LYX_VALIGN_TOP:
2412                         os << 't';
2413                         break;
2414                 case LYX_VALIGN_MIDDLE:
2415                         os << 'm';
2416                         break;
2417                 case LYX_VALIGN_BOTTOM:
2418                         os << 'b';
2419                         break;
2420                 }
2421                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2422                    << "}\n";
2423         }
2424 }
2425
2426
2427 void Tabular::TeXCellPostamble(otexstream & os, idx_type cell,
2428                                bool ismulticol, bool ismultirow) const
2429 {
2430         row_type const r = cellRow(cell);
2431         if (is_long_tabular && row_info[r].caption)
2432                 return;
2433
2434         // usual cells
2435         if (getUsebox(cell) == BOX_PARBOX)
2436                 os << '}';
2437         else if (getUsebox(cell) == BOX_MINIPAGE)
2438                 os << breakln << "\\end{minipage}";
2439         if (getRotateCell(cell) != 0)
2440                 os << breakln << "\\end{turn}";
2441         if (ismultirow)
2442                 os << '}';
2443         if (ismulticol)
2444                 os << '}';
2445 }
2446
2447
2448 void Tabular::TeXLongtableHeaderFooter(otexstream & os,
2449                                         OutputParams const & runparams) const
2450 {
2451         if (!is_long_tabular)
2452                 return;
2453
2454         // caption handling
2455         // output caption which is in no header or footer
2456         if (haveLTCaption()) {
2457                 for (row_type r = 0; r < nrows(); ++r) {
2458                         if (row_info[r].caption &&
2459                             !row_info[r].endfirsthead && !row_info[r].endhead &&
2460                             !row_info[r].endfoot && !row_info[r].endlastfoot)
2461                                 TeXRow(os, r, runparams);
2462                 }
2463         }
2464         // output first header info
2465         if (haveLTFirstHead()) {
2466                 if (endfirsthead.topDL)
2467                         os << "\\hline\n";
2468                 for (row_type r = 0; r < nrows(); ++r) {
2469                         if (row_info[r].endfirsthead)
2470                                 TeXRow(os, r, runparams);
2471                 }
2472                 if (endfirsthead.bottomDL)
2473                         os << "\\hline\n";
2474                 os << "\\endfirsthead\n";
2475         }
2476         // output header info
2477         if (haveLTHead()) {
2478                 if (endfirsthead.empty && !haveLTFirstHead())
2479                         os << "\\endfirsthead\n";
2480                 if (endhead.topDL)
2481                         os << "\\hline\n";
2482                 for (row_type r = 0; r < nrows(); ++r) {
2483                         if (row_info[r].endhead)
2484                                 TeXRow(os, r, runparams);
2485                 }
2486                 if (endhead.bottomDL)
2487                         os << "\\hline\n";
2488                 os << "\\endhead\n";
2489         }
2490         // output footer info
2491         if (haveLTFoot()) {
2492                 if (endfoot.topDL)
2493                         os << "\\hline\n";
2494                 for (row_type r = 0; r < nrows(); ++r) {
2495                         if (row_info[r].endfoot)
2496                                 TeXRow(os, r, runparams);
2497                 }
2498                 if (endfoot.bottomDL)
2499                         os << "\\hline\n";
2500                 os << "\\endfoot\n";
2501                 if (endlastfoot.empty && !haveLTLastFoot())
2502                         os << "\\endlastfoot\n";
2503         }
2504         // output lastfooter info
2505         if (haveLTLastFoot()) {
2506                 if (endlastfoot.topDL)
2507                         os << "\\hline\n";
2508                 for (row_type r = 0; r < nrows(); ++r) {
2509                         if (row_info[r].endlastfoot)
2510                                 TeXRow(os, r, runparams);
2511                 }
2512                 if (endlastfoot.bottomDL)
2513                         os << "\\hline\n";
2514                 os << "\\endlastfoot\n";
2515         }
2516 }
2517
2518
2519 bool Tabular::isValidRow(row_type row) const
2520 {
2521         if (!is_long_tabular)
2522                 return true;
2523         return !row_info[row].endhead && !row_info[row].endfirsthead
2524                 && !row_info[row].endfoot && !row_info[row].endlastfoot
2525                 && !row_info[row].caption;
2526 }
2527
2528
2529 void Tabular::TeXRow(otexstream & os, row_type row,
2530                      OutputParams const & runparams) const
2531 {
2532         idx_type cell = cellIndex(row, 0);
2533         shared_ptr<InsetTableCell> inset = cellInset(cell);
2534         Paragraph const & par = inset->paragraphs().front();
2535         string const lang = par.getParLanguage(buffer().params())->lang();
2536
2537         //output the top line
2538         TeXTopHLine(os, row, lang);
2539
2540         if (row_info[row].top_space_default) {
2541                 if (use_booktabs)
2542                         os << "\\addlinespace\n";
2543                 else
2544                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2545         } else if(!row_info[row].top_space.zero()) {
2546                 if (use_booktabs)
2547                         os << "\\addlinespace["
2548                            << from_ascii(row_info[row].top_space.asLatexString())
2549                            << "]\n";
2550                 else {
2551                         os << "\\noalign{\\vskip"
2552                            << from_ascii(row_info[row].top_space.asLatexString())
2553                            << "}\n";
2554                 }
2555         }
2556         bool ismulticol = false;
2557         bool ismultirow = false;
2558         for (col_type c = 0; c < ncols(); ++c) {
2559                 if (isPartOfMultiColumn(row, c))
2560                         continue;
2561
2562                 cell = cellIndex(row, c);
2563
2564                 if (isPartOfMultiRow(row, c)
2565                     && column_info[c].alignment != LYX_ALIGN_DECIMAL) {
2566                         if (cell != getLastCellInRow(row))
2567                                 os << " & ";
2568                         continue;
2569                 }
2570
2571                 TeXCellPreamble(os, cell, ismulticol, ismultirow);
2572                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2573
2574                 Paragraph const & par = inset->paragraphs().front();
2575
2576                 os.texrow().forceStart(par.id(), 0);
2577
2578                 bool rtl = par.isRTL(buffer().params())
2579                         && !par.empty()
2580                         && getPWidth(cell).zero()
2581                         && !runparams.use_polyglossia;
2582
2583                 if (rtl) {
2584                         string const lang =
2585                                 par.getParLanguage(buffer().params())->lang();
2586                         if (lang == "farsi")
2587                                 os << "\\textFR{";
2588                         else if (lang == "arabic_arabi")
2589                                 os << "\\textAR{";
2590                         // currently, remaining RTL languages are
2591                         // arabic_arabtex and hebrew
2592                         else
2593                                 os << "\\R{";
2594                 }
2595                 // pass to the OutputParams that we are in a cell and
2596                 // which alignment we have set.
2597                 // InsetNewline needs this context information.
2598                 OutputParams newrp(runparams);
2599                 newrp.inTableCell = (getAlignment(cell) == LYX_ALIGN_BLOCK)
2600                                     ? OutputParams::PLAIN
2601                                     : OutputParams::ALIGNED;
2602
2603                 if (getAlignment(cell) == LYX_ALIGN_DECIMAL) {
2604                         // copy cell and split in 2
2605                         InsetTableCell head = InsetTableCell(*cellInset(cell).get());
2606                         head.setBuffer(buffer());
2607                         DocIterator dit = cellInset(cell)->getText(0)->macrocontextPosition();
2608                         dit.pop_back();
2609                         dit.push_back(CursorSlice(head));
2610                         head.setMacrocontextPositionRecursive(dit);
2611                         bool hassep = false;
2612                         InsetTableCell tail = splitCell(head, column_info[c].decimal_point, hassep);
2613                         head.latex(os, newrp);
2614                         if (hassep) {
2615                                 os << '&';
2616                                 tail.setBuffer(head.buffer());
2617                                 dit.pop_back();
2618                                 dit.push_back(CursorSlice(tail));
2619                                 tail.setMacrocontextPositionRecursive(dit);
2620                                 tail.latex(os, newrp);
2621                         }
2622                 } else if (!isPartOfMultiRow(row, c)) {
2623                         if (!runparams.nice)
2624                                 os.texrow().start(par.id(), 0);
2625                         inset->latex(os, newrp);
2626                 }
2627
2628                 runparams.encoding = newrp.encoding;
2629                 if (rtl)
2630                         os << '}';
2631
2632                 TeXCellPostamble(os, cell, ismulticol, ismultirow);
2633                 if (cell != getLastCellInRow(row)) { // not last cell in row
2634                         if (runparams.nice)
2635                                 os << " & ";
2636                         else
2637                                 os << " &\n";
2638                 }
2639         }
2640         os << "\\tabularnewline";
2641         if (row_info[row].bottom_space_default) {
2642                 if (use_booktabs)
2643                         os << "\\addlinespace";
2644                 else
2645                         os << "[\\doublerulesep]";
2646         } else if (!row_info[row].bottom_space.zero()) {
2647                 if (use_booktabs)
2648                         os << "\\addlinespace";
2649                 os << '['
2650                    << from_ascii(row_info[row].bottom_space.asLatexString())
2651                    << ']';
2652         }
2653         os << '\n';
2654
2655         //output the bottom line
2656         TeXBottomHLine(os, row, lang);
2657
2658         if (row_info[row].interline_space_default) {
2659                 if (use_booktabs)
2660                         os << "\\addlinespace\n";
2661                 else
2662                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2663         } else if (!row_info[row].interline_space.zero()) {
2664                 if (use_booktabs)
2665                         os << "\\addlinespace["
2666                            << from_ascii(row_info[row].interline_space.asLatexString())
2667                            << "]\n";
2668                 else
2669                         os << "\\noalign{\\vskip"
2670                            << from_ascii(row_info[row].interline_space.asLatexString())
2671                            << "}\n";
2672         }
2673 }
2674
2675
2676 void Tabular::latex(otexstream & os, OutputParams const & runparams) const
2677 {
2678         bool const is_tabular_star = !tabular_width.zero();
2679         TexRow::RowEntry pos = TexRow::textEntry(runparams.lastid,
2680                                                                                          runparams.lastpos);
2681
2682         //+---------------------------------------------------------------------
2683         //+                      first the opening preamble                    +
2684         //+---------------------------------------------------------------------
2685
2686         os << safebreakln;
2687         if (!TexRow::isNone(pos))
2688                 os.texrow().start(pos);
2689
2690         if (rotate != 0)
2691                 os << "\\begin{turn}{" << convert<string>(rotate) << "}\n";
2692
2693         if (is_long_tabular) {
2694                 os << "\\begin{longtable}";
2695                 switch (longtabular_alignment) {
2696                 case LYX_LONGTABULAR_ALIGN_LEFT:
2697                         os << "[l]";
2698                         break;
2699                 case LYX_LONGTABULAR_ALIGN_CENTER:
2700                         break;
2701                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2702                         os << "[r]";
2703                         break;
2704                 }
2705         } else {
2706                 if (is_tabular_star)
2707                         os << "\\begin{tabular*}{" << from_ascii(tabular_width.asLatexString()) << "}";
2708                 else
2709                         os << "\\begin{tabular}";
2710                 switch (tabular_valignment) {
2711                 case LYX_VALIGN_TOP:
2712                         os << "[t]";
2713                         break;
2714                 case LYX_VALIGN_MIDDLE:
2715                         break;
2716                 case LYX_VALIGN_BOTTOM:
2717                         os << "[b]";
2718                         break;
2719                 }
2720         }
2721
2722         os << "{";
2723
2724         if (is_tabular_star)
2725                 os << "@{\\extracolsep{\\fill}}";
2726
2727         for (col_type c = 0; c < ncols(); ++c) {
2728                 if (columnLeftLine(c))
2729                         os << '|';
2730                 if (!column_info[c].align_special.empty()) {
2731                         os << column_info[c].align_special;
2732                 } else {
2733                         if (!column_info[c].p_width.zero()) {
2734                                 switch (column_info[c].alignment) {
2735                                 case LYX_ALIGN_LEFT:
2736                                         os << ">{\\raggedright}";
2737                                         break;
2738                                 case LYX_ALIGN_RIGHT:
2739                                         os << ">{\\raggedleft}";
2740                                         break;
2741                                 case LYX_ALIGN_CENTER:
2742                                         os << ">{\\centering}";
2743                                         break;
2744                                 case LYX_ALIGN_NONE:
2745                                 case LYX_ALIGN_BLOCK:
2746                                 case LYX_ALIGN_LAYOUT:
2747                                 case LYX_ALIGN_SPECIAL:
2748                                 case LYX_ALIGN_DECIMAL:
2749                                         break;
2750                                 }
2751
2752                                 switch (column_info[c].valignment) {
2753                                 case LYX_VALIGN_TOP:
2754                                         os << 'p';
2755                                         break;
2756                                 case LYX_VALIGN_MIDDLE:
2757                                         os << 'm';
2758                                         break;
2759                                 case LYX_VALIGN_BOTTOM:
2760                                         os << 'b';
2761                                         break;
2762                         }
2763                                 os << '{'
2764                                    << from_ascii(column_info[c].p_width.asLatexString())
2765                                    << '}';
2766                         } else {
2767                                 switch (column_info[c].alignment) {
2768                                 case LYX_ALIGN_LEFT:
2769                                         os << 'l';
2770                                         break;
2771                                 case LYX_ALIGN_RIGHT:
2772                                         os << 'r';
2773                                         break;
2774                                 case LYX_ALIGN_DECIMAL:
2775                                         os << "r@{\\extracolsep{0pt}" << column_info[c].decimal_point << "}l";
2776                                         break;
2777                                 default:
2778                                         os << 'c';
2779                                         break;
2780                                 }
2781                         } // end if else !column_info[i].p_width
2782                 } // end if else !column_info[i].align_special
2783                 if (columnRightLine(c))
2784                         os << '|';
2785         }
2786         os << "}\n";
2787
2788         TeXLongtableHeaderFooter(os, runparams);
2789
2790         //+---------------------------------------------------------------------
2791         //+                      the single row and columns (cells)            +
2792         //+---------------------------------------------------------------------
2793
2794         for (row_type r = 0; r < nrows(); ++r) {
2795                 if (isValidRow(r)) {
2796                         TeXRow(os, r, runparams);
2797                         if (is_long_tabular && row_info[r].newpage)
2798                                 os << "\\newpage\n";
2799                 }
2800         }
2801
2802         //+---------------------------------------------------------------------
2803         //+                      the closing of the tabular                    +
2804         //+---------------------------------------------------------------------
2805
2806         if (is_long_tabular)
2807                 os << "\\end{longtable}";
2808         else {
2809                 if (is_tabular_star)
2810                         os << "\\end{tabular*}";
2811                 else
2812                         os << "\\end{tabular}";
2813         }
2814
2815         if (rotate != 0)
2816                 os << breakln << "\\end{turn}";
2817
2818         if (!TexRow::isNone(pos))
2819                 os.texrow().start(pos);
2820 }
2821
2822
2823 int Tabular::docbookRow(odocstream & os, row_type row,
2824                            OutputParams const & runparams) const
2825 {
2826         int ret = 0;
2827         idx_type cell = getFirstCellInRow(row);
2828
2829         os << "<row>\n";
2830         for (col_type c = 0; c < ncols(); ++c) {
2831                 if (isPartOfMultiColumn(row, c))
2832                         continue;
2833
2834                 os << "<entry align=\"";
2835                 switch (getAlignment(cell)) {
2836                 case LYX_ALIGN_LEFT:
2837                         os << "left";
2838                         break;
2839                 case LYX_ALIGN_RIGHT:
2840                         os << "right";
2841                         break;
2842                 default:
2843                         os << "center";
2844                         break;
2845                 }
2846
2847                 os << "\" valign=\"";
2848                 switch (getVAlignment(cell)) {
2849                 case LYX_VALIGN_TOP:
2850                         os << "top";
2851                         break;
2852                 case LYX_VALIGN_BOTTOM:
2853                         os << "bottom";
2854                         break;
2855                 case LYX_VALIGN_MIDDLE:
2856                         os << "middle";
2857                 }
2858                 os << '"';
2859
2860                 if (isMultiColumn(cell)) {
2861                         os << " namest=\"col" << c << "\" ";
2862                         os << "nameend=\"col" << c + columnSpan(cell) - 1 << '"';
2863                 }
2864
2865                 os << '>';
2866                 ret += cellInset(cell)->docbook(os, runparams);
2867                 os << "</entry>\n";
2868                 ++cell;
2869         }
2870         os << "</row>\n";
2871         return ret;
2872 }
2873
2874
2875 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2876 {
2877         int ret = 0;
2878
2879         //+---------------------------------------------------------------------
2880         //+                      first the opening preamble                    +
2881         //+---------------------------------------------------------------------
2882
2883         os << "<tgroup cols=\"" << ncols()
2884            << "\" colsep=\"1\" rowsep=\"1\">\n";
2885
2886         for (col_type c = 0; c < ncols(); ++c) {
2887                 os << "<colspec colname=\"col" << c << "\" align=\"";
2888                 switch (column_info[c].alignment) {
2889                 case LYX_ALIGN_LEFT:
2890                         os << "left";
2891                         break;
2892                 case LYX_ALIGN_RIGHT:
2893                         os << "right";
2894                         break;
2895                 default:
2896                         os << "center";
2897                         break;
2898                 }
2899                 os << '"';
2900                 if (runparams.flavor == OutputParams::XML)
2901                         os << '/';
2902                 os << ">\n";
2903                 ++ret;
2904         }
2905
2906         //+---------------------------------------------------------------------
2907         //+                      Long Tabular case                             +
2908         //+---------------------------------------------------------------------
2909
2910         // output caption info
2911         // The caption flag wins over head/foot
2912         if (haveLTCaption()) {
2913                 os << "<caption>\n";
2914                 ++ret;
2915                 for (row_type r = 0; r < nrows(); ++r) {
2916                         if (row_info[r].caption) {
2917                                 ret += docbookRow(os, r, runparams);
2918                         }
2919                 }
2920                 os << "</caption>\n";
2921                 ++ret;
2922         }
2923         // output header info
2924         if (haveLTHead(false) || haveLTFirstHead(false)) {
2925                 os << "<thead>\n";
2926                 ++ret;
2927                 for (row_type r = 0; r < nrows(); ++r) {
2928                         if ((row_info[r].endhead || row_info[r].endfirsthead) &&
2929                             !row_info[r].caption) {
2930                                 ret += docbookRow(os, r, runparams);
2931                         }
2932                 }
2933                 os << "</thead>\n";
2934                 ++ret;
2935         }
2936         // output footer info
2937         if (haveLTFoot(false) || haveLTLastFoot(false)) {
2938                 os << "<tfoot>\n";
2939                 ++ret;
2940                 for (row_type r = 0; r < nrows(); ++r) {
2941                         if ((row_info[r].endfoot || row_info[r].endlastfoot) &&
2942                             !row_info[r].caption) {
2943                                 ret += docbookRow(os, r, runparams);
2944                         }
2945                 }
2946                 os << "</tfoot>\n";
2947                 ++ret;
2948         }
2949
2950         //+---------------------------------------------------------------------
2951         //+                      the single row and columns (cells)            +
2952         //+---------------------------------------------------------------------
2953
2954         os << "<tbody>\n";
2955         ++ret;
2956         for (row_type r = 0; r < nrows(); ++r) {
2957                 if (isValidRow(r)) {
2958                         ret += docbookRow(os, r, runparams);
2959                 }
2960         }
2961         os << "</tbody>\n";
2962         ++ret;
2963         //+---------------------------------------------------------------------
2964         //+                      the closing of the tabular                    +
2965         //+---------------------------------------------------------------------
2966
2967         os << "</tgroup>";
2968         ++ret;
2969
2970         return ret;
2971 }
2972
2973
2974 docstring Tabular::xhtmlRow(XHTMLStream & xs, row_type row,
2975                            OutputParams const & runparams, bool header) const
2976 {
2977         docstring ret;
2978         string const celltag = header ? "th" : "td";
2979         idx_type cell = getFirstCellInRow(row);
2980
2981         xs << html::StartTag("tr");
2982         for (col_type c = 0; c < ncols(); ++c) {
2983                 if (isPartOfMultiColumn(row, c) || isPartOfMultiRow(row, c))
2984                         continue;
2985
2986                 stringstream attr;
2987                 attr << "align='";
2988                 switch (getAlignment(cell)) {
2989                 case LYX_ALIGN_LEFT:
2990                         attr << "left";
2991                         break;
2992                 case LYX_ALIGN_RIGHT:
2993                         attr << "right";
2994                         break;
2995                 default:
2996                         attr << "center";
2997                         break;
2998                 }
2999                 attr << "'";
3000                 attr << " valign='";
3001                 switch (getVAlignment(cell)) {
3002                 case LYX_VALIGN_TOP:
3003                         attr << "top";
3004                         break;
3005                 case LYX_VALIGN_BOTTOM:
3006                         attr << "bottom";
3007                         break;
3008                 case LYX_VALIGN_MIDDLE:
3009                         attr << "middle";
3010                 }
3011                 attr << "'";
3012
3013                 if (isMultiColumn(cell))
3014                         attr << " colspan='" << columnSpan(cell) << "'";
3015                 else if (isMultiRow(cell))
3016                         attr << " rowspan='" << rowSpan(cell) << "'";
3017
3018                 xs << html::StartTag(celltag, attr.str()) << html::CR();
3019                 ret += cellInset(cell)->xhtml(xs, runparams);
3020                 xs << html::EndTag(celltag) << html::CR();
3021                 ++cell;
3022         }
3023         xs << html::EndTag("tr");
3024         return ret;
3025 }
3026
3027
3028 docstring Tabular::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
3029 {
3030         docstring ret;
3031
3032         if (is_long_tabular) {
3033                 // we'll wrap it in a div, so as to deal with alignment
3034                 string align;
3035                 switch (longtabular_alignment) {
3036                 case LYX_LONGTABULAR_ALIGN_LEFT:
3037                         align = "left";
3038                         break;
3039                 case LYX_LONGTABULAR_ALIGN_CENTER:
3040                         align = "center";
3041                         break;
3042                 case LYX_LONGTABULAR_ALIGN_RIGHT:
3043                         align = "right";
3044                         break;
3045                 }
3046                 xs << html::StartTag("div", "class='longtable' style='text-align: " + align + ";'")
3047                    << html::CR();
3048                 // The caption flag wins over head/foot
3049                 if (haveLTCaption()) {
3050                         xs << html::StartTag("div", "class='longtable-caption' style='text-align: " + align + ";'")
3051                            << html::CR();
3052                         for (row_type r = 0; r < nrows(); ++r)
3053                                 if (row_info[r].caption)
3054                                         ret += xhtmlRow(xs, r, runparams);
3055                         xs << html::EndTag("div") << html::CR();
3056                 }
3057         }
3058
3059         xs << html::StartTag("table") << html::CR();
3060
3061         // output header info
3062         bool const havefirsthead = haveLTFirstHead(false);
3063         // if we have a first head, then we are going to ignore the
3064         // headers for the additional pages, since there aren't any
3065         // in XHTML. this test accomplishes that.
3066         bool const havehead = !havefirsthead && haveLTHead(false);
3067         if (havehead || havefirsthead) {
3068                 xs << html::StartTag("thead") << html::CR();
3069                 for (row_type r = 0; r < nrows(); ++r) {
3070                         if (((havefirsthead && row_info[r].endfirsthead) ||
3071                              (havehead && row_info[r].endhead)) &&
3072                             !row_info[r].caption) {
3073                                 ret += xhtmlRow(xs, r, runparams, true);
3074                         }
3075                 }
3076                 xs << html::EndTag("thead") << html::CR();
3077         }
3078         // output footer info
3079         bool const havelastfoot = haveLTLastFoot(false);
3080         // as before.
3081         bool const havefoot = !havelastfoot && haveLTFoot(false);
3082         if (havefoot || havelastfoot) {
3083                 xs << html::StartTag("tfoot") << html::CR();
3084                 for (row_type r = 0; r < nrows(); ++r) {
3085                         if (((havelastfoot && row_info[r].endlastfoot) ||
3086                              (havefoot && row_info[r].endfoot)) &&
3087                             !row_info[r].caption) {
3088                                 ret += xhtmlRow(xs, r, runparams);
3089                         }
3090                 }
3091                 xs << html::EndTag("tfoot") << html::CR();
3092         }
3093
3094         xs << html::StartTag("tbody") << html::CR();
3095         for (row_type r = 0; r < nrows(); ++r) {
3096                 if (isValidRow(r)) {
3097                         ret += xhtmlRow(xs, r, runparams);
3098                 }
3099         }
3100         xs << html::EndTag("tbody")
3101            << html::CR()
3102            << html::EndTag("table")
3103            << html::CR();
3104         if (is_long_tabular)
3105                 xs << html::EndTag("div") << html::CR();
3106         return ret;
3107 }
3108
3109
3110 bool Tabular::plaintextTopHLine(odocstringstream & os, row_type row,
3111                                    vector<unsigned int> const & clen) const
3112 {
3113         idx_type const fcell = getFirstCellInRow(row);
3114         idx_type const n = numberOfCellsInRow(row) + fcell;
3115         idx_type tmp = 0;
3116
3117         for (idx_type i = fcell; i < n; ++i) {
3118                 if (topLine(i)) {
3119                         ++tmp;
3120                         break;
3121                 }
3122         }
3123         if (!tmp)
3124                 return false;
3125
3126         char_type ch;
3127         for (idx_type i = fcell; i < n; ++i) {
3128                 if (topLine(i)) {
3129                         if (leftLine(i))
3130                                 os << "+-";
3131                         else
3132                                 os << "--";
3133                         ch = '-';
3134                 } else {
3135                         os << "  ";
3136                         ch = ' ';
3137                 }
3138                 col_type column = cellColumn(i);
3139                 int len = clen[column];
3140                 while (column < ncols() - 1
3141                        && isPartOfMultiColumn(row, ++column))
3142                         len += clen[column] + 4;
3143                 os << docstring(len, ch);
3144                 if (topLine(i)) {
3145                         if (rightLine(i))
3146                                 os << "-+";
3147                         else
3148                                 os << "--";
3149                 } else {
3150                         os << "  ";
3151                 }
3152         }
3153         os << endl;
3154         return true;
3155 }
3156
3157
3158 bool Tabular::plaintextBottomHLine(odocstringstream & os, row_type row,
3159                                       vector<unsigned int> const & clen) const
3160 {
3161         idx_type const fcell = getFirstCellInRow(row);
3162         idx_type const n = numberOfCellsInRow(row) + fcell;
3163         idx_type tmp = 0;
3164
3165         for (idx_type i = fcell; i < n; ++i) {
3166                 if (bottomLine(i)) {
3167                         ++tmp;
3168                         break;
3169                 }
3170         }
3171         if (!tmp)
3172                 return false;
3173
3174         char_type ch;
3175         for (idx_type i = fcell; i < n; ++i) {
3176                 if (bottomLine(i)) {
3177                         if (leftLine(i))
3178                                 os << "+-";
3179                         else
3180                                 os << "--";
3181                         ch = '-';
3182                 } else {
3183                         os << "  ";
3184                         ch = ' ';
3185                 }
3186                 col_type column = cellColumn(i);
3187                 int len = clen[column];
3188                 while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3189                         len += clen[column] + 4;
3190                 os << docstring(len, ch);
3191                 if (bottomLine(i)) {
3192                         if (rightLine(i))
3193                                 os << "-+";
3194                         else
3195                                 os << "--";
3196                 } else {
3197                         os << "  ";
3198                 }
3199         }
3200         os << endl;
3201         return true;
3202 }
3203
3204
3205 void Tabular::plaintextPrintCell(odocstringstream & os,
3206                                OutputParams const & runparams,
3207                                idx_type cell, row_type row, col_type column,
3208                                vector<unsigned int> const & clen,
3209                                bool onlydata, size_t max_length) const
3210 {
3211         odocstringstream sstr;
3212         cellInset(cell)->plaintext(sstr, runparams, max_length);
3213
3214         if (onlydata) {
3215                 os << sstr.str();
3216                 return;
3217         }
3218
3219         if (leftLine(cell))
3220                 os << "| ";
3221         else
3222                 os << "  ";
3223
3224         unsigned int len1 = sstr.str().length();
3225         unsigned int len2 = clen[column];
3226         while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3227                 len2 += clen[column] + 4;
3228         len2 -= len1;
3229
3230         switch (getAlignment(cell)) {
3231         default:
3232         case LYX_ALIGN_LEFT:
3233                 len1 = 0;
3234                 break;
3235         case LYX_ALIGN_RIGHT:
3236                 len1 = len2;
3237                 len2 = 0;
3238                 break;
3239         case LYX_ALIGN_CENTER:
3240                 len1 = len2 / 2;
3241                 len2 -= len1;
3242                 break;
3243         }
3244
3245         os << docstring(len1, ' ') << sstr.str()
3246            << docstring(len2, ' ');
3247
3248         if (rightLine(cell))
3249                 os << " |";
3250         else
3251                 os << "  ";
3252 }
3253
3254
3255 void Tabular::plaintext(odocstringstream & os,
3256                            OutputParams const & runparams, int const depth,
3257                            bool onlydata, char_type delim, size_t max_length) const
3258 {
3259         // first calculate the width of the single columns
3260         vector<unsigned int> clen(ncols());
3261
3262         if (!onlydata) {
3263                 // first all non multicolumn cells!
3264                 for (col_type c = 0; c < ncols(); ++c) {
3265                         clen[c] = 0;
3266                         for (row_type r = 0; r < nrows(); ++r) {
3267                                 idx_type cell = cellIndex(r, c);
3268                                 if (isMultiColumn(cell))
3269                                         continue;
3270                                 odocstringstream sstr;
3271                                 cellInset(cell)->plaintext(sstr, runparams, max_length);
3272                                 if (clen[c] < sstr.str().length())
3273                                         clen[c] = sstr.str().length();
3274                         }
3275                 }
3276                 // then all multicolumn cells!
3277                 for (col_type c = 0; c < ncols(); ++c) {
3278                         for (row_type r = 0; r < nrows(); ++r) {
3279                                 idx_type cell = cellIndex(r, c);
3280                                 if (cell_info[r][c].multicolumn != CELL_BEGIN_OF_MULTICOLUMN)
3281                                         continue;
3282                                 odocstringstream sstr;
3283                                 cellInset(cell)->plaintext(sstr, runparams, max_length);
3284                                 int len = int(sstr.str().length());
3285                                 idx_type const n = columnSpan(cell);
3286                                 for (col_type k = c; len > 0 && k < c + n - 1; ++k)
3287                                         len -= clen[k];
3288                                 if (len > int(clen[c + n - 1]))
3289                                         clen[c + n - 1] = len;
3290                         }
3291                 }
3292         }
3293         idx_type cell = 0;
3294         for (row_type r = 0; r < nrows(); ++r) {
3295                 if (!onlydata && plaintextTopHLine(os, r, clen))
3296                         os << docstring(depth * 2, ' ');
3297                 for (col_type c = 0; c < ncols(); ++c) {
3298                         if (isPartOfMultiColumn(r, c) || isPartOfMultiRow(r,c))
3299                                 continue;
3300                         if (onlydata && c > 0)
3301                                 // we don't use operator<< for single UCS4 character.
3302                                 // see explanation in docstream.h
3303                                 os.put(delim);
3304                         plaintextPrintCell(os, runparams, cell, r, c, clen, onlydata, max_length);
3305                         ++cell;
3306                         if (os.str().size() > max_length)
3307                                 break;
3308                 }
3309                 os << endl;
3310                 if (!onlydata) {
3311                         os << docstring(depth * 2, ' ');
3312                         if (plaintextBottomHLine(os, r, clen))
3313                                 os << docstring(depth * 2, ' ');
3314                 }
3315                 if (os.str().size() > max_length)
3316                         break;
3317         }
3318 }
3319
3320
3321 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
3322 {
3323         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
3324 }
3325
3326
3327 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
3328                                                col_type column) const
3329 {
3330         return cell_info[row][column].inset;
3331 }
3332
3333
3334 void Tabular::setCellInset(row_type row, col_type column,
3335                               shared_ptr<InsetTableCell> ins) const
3336 {
3337         CellData & cd = cell_info[row][column];
3338         cd.inset = ins;
3339 }
3340
3341
3342 void Tabular::validate(LaTeXFeatures & features) const
3343 {
3344         features.require("NeedTabularnewline");
3345         if (use_booktabs)
3346                 features.require("booktabs");
3347         if (is_long_tabular)
3348                 features.require("longtable");
3349         if (needRotating())
3350                 features.require("rotating");
3351         for (idx_type cell = 0; cell < numberofcells; ++cell) {
3352                 if (isMultiRow(cell))
3353                         features.require("multirow");
3354                 if (getVAlignment(cell) != LYX_VALIGN_TOP
3355                     || !getPWidth(cell).zero())
3356                         features.require("array");
3357                 cellInset(cell)->validate(features);
3358         }
3359 }
3360
3361
3362 Tabular::BoxType Tabular::useParbox(idx_type cell) const
3363 {
3364         ParagraphList const & parlist = cellInset(cell)->paragraphs();
3365         ParagraphList::const_iterator cit = parlist.begin();
3366         ParagraphList::const_iterator end = parlist.end();
3367
3368         for (; cit != end; ++cit)
3369                 for (int i = 0; i < cit->size(); ++i)
3370                         if (cit->isNewline(i))
3371                                 return BOX_PARBOX;
3372
3373         return BOX_NONE;
3374 }
3375
3376
3377 /////////////////////////////////////////////////////////////////////
3378 //
3379 // InsetTableCell
3380 //
3381 /////////////////////////////////////////////////////////////////////
3382
3383 InsetTableCell::InsetTableCell(Buffer * buf)
3384         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
3385           contentAlign(LYX_ALIGN_CENTER)
3386 {}
3387
3388
3389 bool InsetTableCell::forcePlainLayout(idx_type) const
3390 {
3391         return !isFixedWidth;
3392 }
3393
3394
3395 bool InsetTableCell::allowParagraphCustomization(idx_type) const
3396 {
3397         return isFixedWidth;
3398 }
3399
3400
3401 bool InsetTableCell::forceLocalFontSwitch() const
3402 {
3403         return isFixedWidth;
3404 }
3405
3406
3407 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
3408         FuncStatus & status) const
3409 {
3410         bool enabled = true;
3411         switch (cmd.action()) {
3412         case LFUN_LAYOUT:
3413                 enabled = !forcePlainLayout();
3414                 break;
3415         case LFUN_LAYOUT_PARAGRAPH:
3416                 enabled = allowParagraphCustomization();
3417                 break;
3418
3419         case LFUN_MATH_DISPLAY:
3420                 if (!hasFixedWidth()) {
3421                         enabled = false;
3422                         break;
3423                 } //fall-through
3424         default:
3425                 return InsetText::getStatus(cur, cmd, status);
3426         }
3427         status.setEnabled(enabled);
3428         return true;
3429 }
3430
3431 docstring InsetTableCell::asString(bool intoInsets)
3432 {
3433         docstring retval;
3434         if (paragraphs().empty())
3435                 return retval;
3436         ParagraphList::const_iterator it = paragraphs().begin();
3437         ParagraphList::const_iterator en = paragraphs().end();
3438         bool first = true;
3439         for (; it != en; ++it) {
3440                 if (!first)
3441                         retval += "\n";
3442                 else
3443                         first = false;
3444                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
3445         }
3446         return retval;
3447 }
3448
3449
3450 void InsetTableCell::addToToc(DocIterator const & di, bool output_active,
3451                                                           UpdateType utype) const
3452 {
3453         InsetText::iterateForToc(di, output_active, utype);
3454 }
3455
3456
3457 docstring InsetTableCell::xhtml(XHTMLStream & xs, OutputParams const & rp) const
3458 {
3459         if (!isFixedWidth)
3460                 return InsetText::insetAsXHTML(xs, rp, InsetText::JustText);
3461         return InsetText::xhtml(xs, rp);
3462 }
3463
3464
3465
3466 /////////////////////////////////////////////////////////////////////
3467 //
3468 // InsetTabular
3469 //
3470 /////////////////////////////////////////////////////////////////////
3471
3472 InsetTabular::InsetTabular(Buffer * buf, row_type rows,
3473                            col_type columns)
3474         : Inset(buf), tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))),
3475           first_visible_cell_(0), offset_valign_(0), rowselect_(false), colselect_(false)
3476 {
3477 }
3478
3479
3480 InsetTabular::InsetTabular(InsetTabular const & tab)
3481         : Inset(tab), tabular(tab.tabular)
3482 {
3483 }
3484
3485
3486 InsetTabular::~InsetTabular()
3487 {
3488         hideDialogs("tabular", this);
3489 }
3490
3491
3492 void InsetTabular::setBuffer(Buffer & buf)
3493 {
3494         tabular.setBuffer(buf);
3495         Inset::setBuffer(buf);
3496 }
3497
3498
3499 bool InsetTabular::insetAllowed(InsetCode code) const
3500 {
3501         switch (code) {
3502         case FLOAT_CODE:
3503         case MARGIN_CODE:
3504         case MATHMACRO_CODE:
3505         case WRAP_CODE:
3506                 return false;
3507
3508         case CAPTION_CODE:
3509                 return tabular.is_long_tabular;
3510
3511         default:
3512                 return true;
3513         }
3514 }
3515
3516
3517 bool InsetTabular::allowsCaptionVariation(std::string const & newtype) const
3518 {
3519         return tabular.is_long_tabular &&
3520                 (newtype == "Standard" || newtype == "LongTableNoNumber");
3521 }
3522
3523
3524 void InsetTabular::write(ostream & os) const
3525 {
3526         os << "Tabular" << endl;
3527         tabular.write(os);
3528 }
3529
3530
3531 string InsetTabular::contextMenu(BufferView const &, int, int) const
3532 {
3533         // FIXME: depending on the selection state,
3534         // we could offer a different menu.
3535         return cell(0)->contextMenuName() + ";" + contextMenuName();
3536 }
3537
3538
3539 string InsetTabular::contextMenuName() const
3540 {
3541         return "context-tabular";
3542 }
3543
3544
3545 void InsetTabular::read(Lexer & lex)
3546 {
3547         //bool const old_format = (lex.getString() == "\\LyXTable");
3548
3549         tabular.read(lex);
3550
3551         //if (old_format)
3552         //      return;
3553
3554         lex.next();
3555         string token = lex.getString();
3556         while (lex && token != "\\end_inset") {
3557                 lex.next();
3558                 token = lex.getString();
3559         }
3560         if (!lex)
3561                 lex.printError("Missing \\end_inset at this point. ");
3562 }
3563
3564
3565 int InsetTabular::rowFromY(Cursor & cur, int y) const
3566 {
3567         // top y coordinate of tabular
3568         int h = yo(cur.bv()) - tabular.rowAscent(0) + offset_valign_;
3569         row_type r = 0;
3570         for (; r < tabular.nrows() && y > h; ++r)
3571                 h += tabular.rowAscent(r) + tabular.rowDescent(r)
3572                         + tabular.interRowSpace(r);
3573
3574         return r - 1;
3575 }
3576
3577
3578 int InsetTabular::columnFromX(Cursor & cur, int x) const
3579 {
3580         // left x coordinate of tabular
3581         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3582         col_type c = 0;
3583         for (; c < tabular.ncols() && x > w; ++c)
3584                 w += tabular.cellWidth(c);
3585         return c - 1;
3586 }
3587
3588
3589 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3590 {
3591         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3592         //      mi.base.textwidth << "\n";
3593         LBUFERR(mi.base.bv);
3594
3595         for (row_type r = 0; r < tabular.nrows(); ++r) {
3596                 int maxasc = 0;
3597                 int maxdes = 0;
3598                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3599                         if (tabular.isPartOfMultiColumn(r, c)
3600                                 || tabular.isPartOfMultiRow(r, c))
3601                                 // multicolumn or multirow cell, but not first one
3602                                 continue;
3603                         idx_type const cell = tabular.cellIndex(r, c);
3604                         Dimension dim;
3605                         MetricsInfo m = mi;
3606                         Length const p_width = tabular.getPWidth(cell);
3607                         if (!p_width.zero())
3608                                 m.base.textwidth = p_width.inPixels(mi.base);
3609                         tabular.cellInset(cell)->metrics(m, dim);
3610                         if (!p_width.zero())
3611                                 dim.wid = m.base.textwidth;
3612                         tabular.cellInfo(cell).width = dim.wid + 2 * WIDTH_OF_LINE
3613                                 + tabular.interColumnSpace(cell);
3614
3615                         // FIXME(?): do we need a second metrics call?
3616                         TextMetrics const & tm =
3617                                 mi.base.bv->textMetrics(tabular.cellInset(cell)->getText(0));
3618
3619                         // determine horizontal offset because of decimal align (if necessary)
3620                         int decimal_width = 0;
3621                         if (tabular.getAlignment(cell) == LYX_ALIGN_DECIMAL) {
3622                                 InsetTableCell tail = InsetTableCell(*tabular.cellInset(cell).get());
3623                                 tail.setBuffer(tabular.buffer());
3624                                 // we need to set macrocontext position everywhere
3625                                 // otherwise we crash with nested insets (e.g. footnotes)
3626                                 // after decimal point
3627                                 DocIterator dit = tabular.cellInset(cell)->getText(0)->macrocontextPosition();
3628                                 dit.pop_back();
3629                                 dit.push_back(CursorSlice(tail));
3630                                 tail.setMacrocontextPositionRecursive(dit);
3631
3632                                 // remove text leading decimal point
3633                                 docstring const align_d = tabular.column_info[c].decimal_point;
3634                                 dit = separatorPos(&tail, align_d);
3635
3636                                 pit_type const psize = tail.paragraphs().front().size();
3637                                 if (dit) {
3638                                         tail.paragraphs().front().eraseChars(0,
3639                                                 dit.pos() < psize ? dit.pos() + 1 : psize, false);
3640                                         Dimension dim1;
3641                                         tail.metrics(m, dim1);
3642                                         decimal_width = dim1.width();
3643                                 }
3644                         }
3645                         tabular.cell_info[r][c].decimal_hoffset = tm.width() - decimal_width;
3646                         tabular.cell_info[r][c].decimal_width = decimal_width;
3647
3648                         // with LYX_VALIGN_BOTTOM the descent is relative to the last par
3649                         // = descent of text in last par + TEXT_TO_INSET_OFFSET:
3650                         int const lastpardes = tm.last().second->descent()
3651                                 + TEXT_TO_INSET_OFFSET;
3652                         int offset = 0;
3653                         switch (tabular.getVAlignment(cell)) {
3654                                 case Tabular::LYX_VALIGN_TOP:
3655                                         break;
3656                                 case Tabular::LYX_VALIGN_MIDDLE:
3657                                         offset = -(dim.des - lastpardes)/2;
3658                                         break;
3659                                 case Tabular::LYX_VALIGN_BOTTOM:
3660                                         offset = -(dim.des - lastpardes);
3661                                         break;
3662                         }
3663                         tabular.cell_info[r][c].voffset = offset;
3664                         maxasc = max(maxasc, dim.asc - offset);
3665                         maxdes = max(maxdes, dim.des + offset);
3666                 }
3667                 int const top_space = tabular.row_info[r].top_space_default ?
3668                         default_line_space :
3669                         tabular.row_info[r].top_space.inPixels(mi.base);
3670                 tabular.setRowAscent(r, maxasc + ADD_TO_HEIGHT + top_space);
3671                 int const bottom_space = tabular.row_info[r].bottom_space_default ?
3672                         default_line_space :
3673                         tabular.row_info[r].bottom_space.inPixels(mi.base);
3674                 tabular.setRowDescent(r, maxdes + ADD_TO_HEIGHT + bottom_space);
3675         }
3676
3677         // for top-alignment the first horizontal table line must be exactly at
3678         // the position of the base line of the surrounding text line
3679         // for bottom alignment, the same is for the last table line
3680         switch (tabular.tabular_valignment) {
3681         case Tabular::LYX_VALIGN_BOTTOM:
3682                 offset_valign_ = tabular.rowAscent(0) - tabular.height();
3683                 break;
3684         case Tabular::LYX_VALIGN_MIDDLE:
3685                 offset_valign_ = (- tabular.height()) / 2 + tabular.rowAscent(0);
3686                 break;
3687         case Tabular::LYX_VALIGN_TOP:
3688                 offset_valign_ = tabular.rowAscent(0);
3689                 break;
3690         }
3691
3692         tabular.updateColumnWidths();
3693         dim.asc = tabular.rowAscent(0) - offset_valign_;
3694         dim.des = tabular.height() - dim.asc;
3695         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3696 }
3697
3698
3699 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col)
3700         const
3701 {
3702         if (&cur.inset() == this && cur.selection()) {
3703                 if (cur.selIsMultiCell()) {
3704                         row_type rs, re;
3705                         col_type cs, ce;
3706                         getSelection(cur, rs, re, cs, ce);
3707
3708                         idx_type const cell = tabular.cellIndex(row, col);
3709                         col_type const cspan = tabular.columnSpan(cell);
3710                         row_type const rspan = tabular.rowSpan(cell);
3711                         if (col + cspan - 1 >= cs && col <= ce
3712                                 && row + rspan - 1 >= rs && row <= re)
3713                                 return true;
3714                 } else
3715                         if (col == tabular.cellColumn(cur.idx())
3716                                 && row == tabular.cellRow(cur.idx())) {
3717                         CursorSlice const & beg = cur.selBegin();
3718                         CursorSlice const & end = cur.selEnd();
3719
3720                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3721                                   && end.pos() == end.lastpos() && beg.pos() == 0
3722                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3723                                 return true;
3724                 }
3725         }
3726         return false;
3727 }
3728
3729
3730 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3731 {
3732         x += ADD_TO_TABULAR_WIDTH;
3733
3734         BufferView * bv = pi.base.bv;
3735         Cursor & cur = pi.base.bv->cursor();
3736
3737         // FIXME: As the full background is painted in drawBackground(),
3738         // we have no choice but to do a full repaint for the Text cells.
3739         pi.full_repaint = true;
3740
3741         bool const original_selection_state = pi.selected;
3742
3743         idx_type idx = 0;
3744         first_visible_cell_ = Tabular::npos;
3745
3746         int yy = y + offset_valign_;
3747         for (row_type r = 0; r < tabular.nrows(); ++r) {
3748                 int nx = x;
3749                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3750                         if (tabular.isPartOfMultiColumn(r, c))
3751                                 continue;
3752
3753                         idx = tabular.cellIndex(r, c);
3754
3755                         if (tabular.isPartOfMultiRow(r, c)) {
3756                                 nx += tabular.cellWidth(idx);
3757                                 continue;
3758                         }
3759
3760                         if (first_visible_cell_ == Tabular::npos)
3761                                 first_visible_cell_ = idx;
3762
3763                         pi.selected |= isCellSelected(cur, r, c);
3764                         int const cx = nx + tabular.textHOffset(idx);
3765                         int const cy = yy + tabular.textVOffset(idx);
3766                         // Cache the Inset position.
3767                         bv->coordCache().insets().add(cell(idx).get(), cx, cy);
3768                         cell(idx)->draw(pi, cx, cy);
3769                         drawCellLines(pi, nx, yy, r, idx);
3770                         nx += tabular.cellWidth(idx);
3771                         pi.selected = original_selection_state;
3772                 }
3773
3774                 if (r + 1 < tabular.nrows())
3775                         yy += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3776                                 + tabular.interRowSpace(r + 1);
3777         }
3778 }
3779
3780
3781 void InsetTabular::drawBackground(PainterInfo & pi, int x, int y) const
3782 {
3783         x += ADD_TO_TABULAR_WIDTH;
3784         y += offset_valign_ - tabular.rowAscent(0);
3785         pi.pain.fillRectangle(x, y, tabular.width(), tabular.height(),
3786                 pi.backgroundColor(this));
3787 }
3788
3789
3790 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3791 {
3792         Cursor & cur = pi.base.bv->cursor();
3793
3794         x += ADD_TO_TABULAR_WIDTH;
3795
3796         if (!cur.selection())
3797                 return;
3798         if (&cur.inset() != this)
3799                 return;
3800
3801         //resetPos(cur);
3802
3803         bool const full_cell_selected = isCellSelected(cur,
3804                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3805
3806         if (cur.selIsMultiCell() || full_cell_selected) {
3807                 for (row_type r = 0; r < tabular.nrows(); ++r) {
3808                         int xx = x;
3809                         for (col_type c = 0; c < tabular.ncols(); ++c) {
3810                                 if (tabular.isPartOfMultiColumn(r, c))
3811                                         continue;
3812
3813                                 idx_type const cell = tabular.cellIndex(r, c);
3814
3815                                 if (tabular.isPartOfMultiRow(r, c)) {
3816                                         xx += tabular.cellWidth(cell);
3817                                         continue;
3818                                 }
3819                                 int const w = tabular.cellWidth(cell);
3820                                 int const h = tabular.cellHeight(cell);
3821                                 int const yy = y - tabular.rowAscent(r) + offset_valign_;
3822                                 if (isCellSelected(cur, r, c))
3823                                         pi.pain.fillRectangle(xx, yy, w, h, Color_selection);
3824                                 xx += w;
3825                         }
3826                         if (r + 1 < tabular.nrows())
3827                                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3828                                      + tabular.interRowSpace(r + 1);
3829                 }
3830
3831         }
3832         // FIXME: This code has no effect because InsetTableCell does not handle
3833         // drawSelection other than the trivial implementation in Inset.
3834         //else {
3835         //      x += cellXPos(cur.idx());
3836         //      x += tabular.textHOffset(cur.idx());
3837         //      cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3838         //}
3839 }
3840
3841
3842 void InsetTabular::drawCellLines(PainterInfo & pi, int x, int y,
3843                                  row_type row, idx_type cell) const
3844 {
3845         y -= tabular.rowAscent(row);
3846         int const w = tabular.cellWidth(cell);
3847         int const h = tabular.cellHeight(cell);
3848         Color const linecolor = pi.textColor(Color_tabularline);
3849         Color const gridcolor = pi.textColor(Color_tabularonoffline);
3850
3851         // Top
3852         bool drawline = tabular.topLine(cell)
3853                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
3854         pi.pain.line(x, y, x + w, y,
3855                 drawline ? linecolor : gridcolor,
3856                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3857
3858         // Bottom
3859         drawline = tabular.bottomLine(cell);
3860         pi.pain.line(x, y + h, x + w, y + h,
3861                 drawline ? linecolor : gridcolor,
3862                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3863
3864         // Left
3865         col_type const col = tabular.cellColumn(cell);
3866         drawline = tabular.leftLine(cell)
3867                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
3868         pi.pain.line(x, y, x, y + h,
3869                 drawline ? linecolor : gridcolor,
3870                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3871
3872         // Right
3873         x -= tabular.interColumnSpace(cell);
3874         col_type next_cell_col = col + 1;
3875         while (next_cell_col < tabular.ncols()
3876                 && tabular.isMultiColumn(tabular.cellIndex(row, next_cell_col)))
3877                 next_cell_col++;
3878         drawline = tabular.rightLine(cell)
3879                    || (next_cell_col < tabular.ncols()
3880                        && tabular.leftLine(tabular.cellIndex(row, next_cell_col)));
3881         pi.pain.line(x + w, y, x + w, y + h,
3882                 drawline ? linecolor : gridcolor,
3883                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3884 }
3885
3886
3887 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3888 {
3889         //lyxerr << "InsetTabular::edit: " << this << endl;
3890         cur.finishUndo();
3891         cur.push(*this);
3892         if (front) {
3893                 if (isRightToLeft(cur))
3894                         cur.idx() = tabular.getLastCellInRow(0);
3895                 else
3896                         cur.idx() = 0;
3897                 cur.pit() = 0;
3898                 cur.pos() = 0;
3899         } else {
3900                 if (isRightToLeft(cur))
3901                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
3902                 else
3903                         cur.idx() = tabular.numberofcells - 1;
3904                 cur.pit() = 0;
3905                 cur.pos() = cur.lastpos(); // FIXME crude guess
3906         }
3907         cur.setCurrentFont();
3908         // FIXME: this accesses the position cache before it is initialized
3909         //cur.bv().fitCursor();
3910 }
3911
3912
3913 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
3914 {
3915         // In a longtable, tell captions what the current float is
3916         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3917         string const saveflt = cnts.current_float();
3918         if (tabular.is_long_tabular) {
3919                 cnts.current_float("table");
3920                 // in longtables, we only step the counter once
3921                 cnts.step(from_ascii("table"), utype);
3922                 cnts.isLongtable(true);
3923         }
3924
3925         ParIterator it2 = it;
3926         it2.forwardPos();
3927         size_t const end = it2.nargs();
3928         for ( ; it2.idx() < end; it2.top().forwardIdx())
3929                 buffer().updateBuffer(it2, utype);
3930
3931         //reset afterwards
3932         if (tabular.is_long_tabular) {
3933                 cnts.current_float(saveflt);
3934                 cnts.isLongtable(false);
3935         }
3936 }
3937
3938
3939 void InsetTabular::addToToc(DocIterator const & cpit, bool output_active,
3940                                                         UpdateType utype) const
3941 {
3942         DocIterator dit = cpit;
3943         dit.forwardPos();
3944         size_t const end = dit.nargs();
3945         for ( ; dit.idx() < end; dit.top().forwardIdx())
3946                 cell(dit.idx())->addToToc(dit, output_active, utype);
3947 }
3948
3949
3950 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3951 {
3952         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3953                              << "\n  cur:" << cur);
3954         CursorSlice sl = cur.top();
3955         Cursor & bvcur = cur.bv().cursor();
3956
3957         FuncCode const act = cmd.action();
3958
3959         switch (act) {
3960
3961         case LFUN_MOUSE_PRESS: {
3962                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3963                 // select row
3964                 if (cmd.x() < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3965                         || cmd.x() > xo(cur.bv()) + tabular.width()) {
3966                         row_type r = rowFromY(cur, cmd.y());
3967                         cur.idx() = tabular.getFirstCellInRow(r);
3968                         cur.pos() = 0;
3969                         cur.resetAnchor();
3970                         cur.idx() = tabular.getLastCellInRow(r);
3971                         cur.pos() = cur.lastpos();
3972                         cur.setSelection(true);
3973                         bvcur = cur;
3974                         rowselect_ = true;
3975                         break;
3976                 }
3977                 // select column
3978                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0) + offset_valign_;
3979                 if (cmd.y() < y0 + ADD_TO_TABULAR_WIDTH
3980                         || cmd.y() > y0 + tabular.height()) {
3981                         col_type c = columnFromX(cur, cmd.x());
3982                         cur.idx() = tabular.cellIndex(0, c);
3983                         cur.pos() = 0;
3984                         cur.resetAnchor();
3985                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3986                         cur.pos() = cur.lastpos();
3987                         cur.setSelection(true);
3988                         bvcur = cur;
3989                         colselect_ = true;
3990                         break;
3991                 }
3992                 // do not reset cursor/selection if we have selected
3993                 // some cells (bug 2715).
3994                 if (cmd.button() == mouse_button::button3
3995                     && &bvcur.selBegin().inset() == this
3996                     && bvcur.selIsMultiCell())
3997                         ;
3998                 else
3999                         // Let InsetTableCell do it
4000                         cell(cur.idx())->dispatch(cur, cmd);
4001                 break;
4002         }
4003         case LFUN_MOUSE_MOTION:
4004                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
4005                 if (cmd.button() == mouse_button::button1) {
4006                         // only accept motions to places not deeper nested than the real anchor
4007                         if (!bvcur.realAnchor().hasPart(cur)) {
4008                                 cur.undispatched();
4009                                 break;
4010                         }
4011                         // select (additional) row
4012                         if (rowselect_) {
4013                                 row_type r = rowFromY(cur, cmd.y());
4014                                 cur.idx() = tabular.getLastCellInRow(r);
4015                                 // we need to reset the cursor's pit and pos now, as the old ones
4016                                 // may no longer be valid.
4017                                 cur.pit() = 0;
4018                                 cur.pos() = 0;
4019                                 bvcur.setCursor(cur);
4020                                 bvcur.setSelection(true);
4021                                 break;
4022                         }
4023                         // select (additional) column
4024                         if (colselect_) {
4025                                 col_type c = columnFromX(cur, cmd.x());
4026                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
4027                                 // we need to reset the cursor's pit and pos now, as the old ones
4028                                 // may no longer be valid.
4029                                 cur.pit() = 0;
4030                                 cur.pos() = 0;
4031                                 bvcur.setCursor(cur);
4032                                 bvcur.setSelection(true);
4033                                 break;
4034                         }
4035                         // only update if selection changes
4036                         if (bvcur.idx() == cur.idx() &&
4037                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
4038                                 cur.noScreenUpdate();
4039                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
4040                         bvcur.setCursor(cur);
4041                         bvcur.setSelection(true);
4042                         // if this is a multicell selection, we just set the cursor to
4043                         // the beginning of the cell's text.
4044                         if (bvcur.selIsMultiCell()) {
4045                                 bvcur.pit() = bvcur.lastpit();
4046                                 bvcur.pos() = bvcur.lastpos();
4047                         }
4048                 }
4049                 break;
4050
4051         case LFUN_MOUSE_RELEASE:
4052                 rowselect_ = false;
4053                 colselect_ = false;
4054                 break;
4055
4056         case LFUN_CELL_BACKWARD:
4057                 movePrevCell(cur);
4058                 cur.setSelection(false);
4059                 break;
4060
4061         case LFUN_CELL_FORWARD:
4062                 moveNextCell(cur);
4063                 cur.setSelection(false);
4064                 break;
4065
4066         case LFUN_CHAR_FORWARD_SELECT:
4067         case LFUN_CHAR_FORWARD:
4068         case LFUN_CHAR_BACKWARD_SELECT:
4069         case LFUN_CHAR_BACKWARD:
4070         case LFUN_CHAR_RIGHT_SELECT:
4071         case LFUN_CHAR_RIGHT:
4072         case LFUN_CHAR_LEFT_SELECT:
4073         case LFUN_CHAR_LEFT:
4074         case LFUN_WORD_FORWARD:
4075         case LFUN_WORD_FORWARD_SELECT:
4076         case LFUN_WORD_BACKWARD:
4077         case LFUN_WORD_BACKWARD_SELECT:
4078         case LFUN_WORD_RIGHT:
4079         case LFUN_WORD_RIGHT_SELECT:
4080         case LFUN_WORD_LEFT:
4081         case LFUN_WORD_LEFT_SELECT: {
4082                 // determine whether we move to next or previous cell, where to enter
4083                 // the new cell from, and which command to "finish" (i.e., exit the
4084                 // inset) with:
4085                 bool next_cell;
4086                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
4087                 FuncCode finish_lfun;
4088
4089                 if (act == LFUN_CHAR_FORWARD
4090                                 || act == LFUN_CHAR_FORWARD_SELECT
4091                                 || act == LFUN_WORD_FORWARD
4092                                 || act == LFUN_WORD_FORWARD_SELECT) {
4093                         next_cell = true;
4094                         finish_lfun = LFUN_FINISHED_FORWARD;
4095                 }
4096                 else if (act == LFUN_CHAR_BACKWARD
4097                                 || act == LFUN_CHAR_BACKWARD_SELECT
4098                                 || act == LFUN_WORD_BACKWARD
4099                                 || act == LFUN_WORD_BACKWARD_SELECT) {
4100                         next_cell = false;
4101                         finish_lfun = LFUN_FINISHED_BACKWARD;
4102                 }
4103                 // LEFT or RIGHT commands --- the interpretation will depend on the
4104                 // table's direction.
4105                 else {
4106                         bool const right = act == LFUN_CHAR_RIGHT
4107                                 || act == LFUN_CHAR_RIGHT_SELECT
4108                                 || act == LFUN_WORD_RIGHT
4109                                 || act == LFUN_WORD_RIGHT_SELECT;
4110                         next_cell = isRightToLeft(cur) != right;
4111
4112                         if (lyxrc.visual_cursor)
4113                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
4114
4115                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
4116                 }
4117
4118                 bool const select =     act == LFUN_CHAR_FORWARD_SELECT
4119                     || act == LFUN_CHAR_BACKWARD_SELECT
4120                     || act == LFUN_CHAR_RIGHT_SELECT
4121                     || act == LFUN_CHAR_LEFT_SELECT
4122                         || act == LFUN_WORD_FORWARD_SELECT
4123                         || act == LFUN_WORD_RIGHT_SELECT
4124                         || act == LFUN_WORD_BACKWARD_SELECT
4125                         || act == LFUN_WORD_LEFT_SELECT;
4126
4127                 // If we have a multicell selection or we're
4128                 // not doing some LFUN_*_SELECT thing anyway...
4129                 if (!cur.selIsMultiCell() || !select) {
4130                         col_type const c = tabular.cellColumn(cur.idx());
4131                         row_type const r = tabular.cellRow(cur.idx());
4132                         // Are we trying to select the whole cell and is the whole cell
4133                         // not yet selected?
4134                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
4135                                 ((next_cell && cur.pit() == cur.lastpit()
4136                                 && cur.pos() == cur.lastpos())
4137                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
4138
4139                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
4140
4141                         // ...try to dispatch to the cell's inset.
4142                         cell(cur.idx())->dispatch(cur, cmd);
4143
4144                         // When we already have a selection we want to select the whole cell
4145                         // before going to the next cell.
4146                         if (select_whole && !empty_cell){
4147                                 getText(cur.idx())->selectAll(cur);
4148                                 cur.dispatched();
4149                                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4150                                 break;
4151                         }
4152
4153                         // FIXME: When we support the selection of an empty cell, remove
4154                         // the !empty_cell from this condition. For now we jump to the next
4155                         // cell if the current cell is empty.
4156                         if (cur.result().dispatched() && !empty_cell)
4157                                 break;
4158                 }
4159
4160                 // move to next/prev cell, as appropriate
4161                 // note that we will always do this if we're selecting and we have
4162                 // a multicell selection
4163                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
4164                         << " cell from: " << int(entry_from));
4165                 if (next_cell)
4166                         moveNextCell(cur, entry_from);
4167                 else
4168                         movePrevCell(cur, entry_from);
4169                 // if we're exiting the table, call the appropriate FINISHED lfun
4170                 if (sl == cur.top()) {
4171                         cmd = FuncRequest(finish_lfun);
4172                         cur.undispatched();
4173                 } else
4174                         cur.dispatched();
4175
4176                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4177                 break;
4178
4179         }
4180
4181         case LFUN_DOWN_SELECT:
4182         case LFUN_DOWN:
4183                 if (!(cur.selection() && cur.selIsMultiCell()))
4184                         cell(cur.idx())->dispatch(cur, cmd);
4185
4186                 cur.dispatched(); // override the cell's decision
4187                 if (sl == cur.top()) {
4188                         // if our Text didn't do anything to the cursor
4189                         // then we try to put the cursor into the cell below
4190                         // setting also the right targetX.
4191                         cur.selHandle(act == LFUN_DOWN_SELECT);
4192                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
4193                                 int const xtarget = cur.targetX();
4194                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4195                                 // an inconsistent state until pos() has been set. Be careful
4196                                 // what you do with it!
4197                                 cur.idx() = tabular.cellBelow(cur.idx());
4198                                 cur.pit() = 0;
4199                                 TextMetrics const & tm =
4200                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
4201                                 cur.pos() = tm.x2pos(cur.pit(), 0, xtarget);
4202                                 cur.setCurrentFont();
4203                         }
4204                 }
4205                 if (sl == cur.top()) {
4206                         // we trick it to go to forward after leaving the
4207                         // tabular.
4208                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
4209                         cur.undispatched();
4210                 }
4211                 if (cur.selIsMultiCell()) {
4212                         cur.pit() = cur.lastpit();
4213                         cur.pos() = cur.lastpos();
4214                         cur.setCurrentFont();
4215                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4216                         return;
4217                 }
4218                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4219                 break;
4220
4221         case LFUN_UP_SELECT:
4222         case LFUN_UP:
4223                 if (!(cur.selection() && cur.selIsMultiCell()))
4224                         cell(cur.idx())->dispatch(cur, cmd);
4225                 cur.dispatched(); // override the cell's decision
4226                 if (sl == cur.top()) {
4227                         // if our Text didn't do anything to the cursor
4228                         // then we try to put the cursor into the cell above
4229                         // setting also the right targetX.
4230                         cur.selHandle(act == LFUN_UP_SELECT);
4231                         if (tabular.cellRow(cur.idx()) != 0) {
4232                                 int const xtarget = cur.targetX();
4233                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4234                                 // an inconsistent state until pos() has been set. Be careful
4235                                 // what you do with it!
4236                                 cur.idx() = tabular.cellAbove(cur.idx());
4237                                 cur.pit() = cur.lastpit();
4238                                 Text const * text = cell(cur.idx())->getText(0);
4239                                 TextMetrics const & tm = cur.bv().textMetrics(text);
4240                                 ParagraphMetrics const & pm =
4241                                         tm.parMetrics(cur.lastpit());
4242                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, xtarget);
4243                                 cur.setCurrentFont();
4244                         }
4245                 }
4246                 if (sl == cur.top()) {
4247                         cmd = FuncRequest(LFUN_UP);
4248                         cur.undispatched();
4249                 }
4250                 if (cur.selIsMultiCell()) {
4251                         cur.pit() = 0;
4252                         cur.pos() = cur.lastpos();
4253                         cur.setCurrentFont();
4254                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4255                         return;
4256                 }
4257                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4258                 break;
4259
4260 //      case LFUN_SCREEN_DOWN: {
4261 //              //if (hasSelection())
4262 //              //      cur.selection() = false;
4263 //              col_type const col = tabular.cellColumn(cur.idx());
4264 //              int const t =   cur.bv().top_y() + cur.bv().height();
4265 //              if (t < yo() + tabular.getHeightOfTabular()) {
4266 //                      cur.bv().scrollDocView(t, true);
4267 //                      cur.idx() = tabular.cellBelow(first_visible_cell_) + col;
4268 //              } else {
4269 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
4270 //              }
4271 //              cur.par() = 0;
4272 //              cur.pos() = 0;
4273 //              break;
4274 //      }
4275 //
4276 //      case LFUN_SCREEN_UP: {
4277 //              //if (hasSelection())
4278 //              //      cur.selection() = false;
4279 //              col_type const col = tabular.cellColumn(cur.idx());
4280 //              int const t =   cur.bv().top_y() + cur.bv().height();
4281 //              if (yo() < 0) {
4282 //                      cur.bv().scrollDocView(t, true);
4283 //                      if (yo() > 0)
4284 //                              cur.idx() = col;
4285 //                      else
4286 //                              cur.idx() = tabular.cellBelow(first_visible_cell_) + col;
4287 //              } else {
4288 //                      cur.idx() = col;
4289 //              }
4290 //              cur.par() = cur.lastpar();
4291 //              cur.pos() = cur.lastpos();
4292 //              break;
4293 //      }
4294
4295         case LFUN_LAYOUT_TABULAR:
4296                 cur.bv().showDialog("tabular");
4297                 break;
4298
4299         case LFUN_INSET_MODIFY: {
4300                 string arg;
4301                 if (cmd.getArg(1) == "from-dialog")
4302                         arg = cmd.getArg(0) + to_utf8(cmd.argument().substr(19));
4303                 else
4304                         arg = to_utf8(cmd.argument());
4305                 if (!tabularFeatures(cur, arg))
4306                         cur.undispatched();
4307                 break;
4308         }
4309
4310         // insert file functions
4311         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
4312         case LFUN_FILE_INSERT_PLAINTEXT:
4313                 // FIXME UNICODE
4314                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
4315                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
4316                                 FileName(to_utf8(cmd.argument())));
4317                         if (tmpstr.empty())
4318                                 break;
4319                         cur.recordUndoInset();
4320                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
4321                                 // content has been replaced,
4322                                 // so cursor might be invalid
4323                                 cur.pos() = cur.lastpos();
4324                                 cur.pit() = cur.lastpit();
4325                                 bvcur.setCursor(cur);
4326                         } else
4327                                 cur.undispatched();
4328                 }
4329                 break;
4330
4331         case LFUN_CUT:
4332                 if (cur.selIsMultiCell()) {
4333                         if (copySelection(cur)) {
4334                                 cur.recordUndoInset();
4335                                 cutSelection(cur);
4336                         }
4337                 } else
4338                         cell(cur.idx())->dispatch(cur, cmd);
4339                 break;
4340
4341         case LFUN_SELF_INSERT:
4342                 if (cur.selIsMultiCell()) {
4343                         cur.recordUndoInset();
4344                         cutSelection(cur);
4345                         BufferView * bv = &cur.bv();
4346                         docstring::const_iterator cit = cmd.argument().begin();
4347                         docstring::const_iterator const end = cmd.argument().end();
4348                         for (; cit != end; ++cit)
4349                                 bv->translateAndInsert(*cit, getText(cur.idx()), cur);
4350
4351                         cur.resetAnchor();
4352                         bv->bookmarkEditPosition();
4353                 } else
4354                         cell(cur.idx())->dispatch(cur, cmd);
4355                 break;
4356
4357         case LFUN_CHAR_DELETE_BACKWARD:
4358         case LFUN_CHAR_DELETE_FORWARD:
4359                 if (cur.selIsMultiCell()) {
4360                         cur.recordUndoInset();
4361                         cutSelection(cur);
4362                 } else
4363                         cell(cur.idx())->dispatch(cur, cmd);
4364                 break;
4365
4366         case LFUN_COPY:
4367                 if (!cur.selection())
4368                         break;
4369                 if (cur.selIsMultiCell()) {
4370                         cur.finishUndo();
4371                         copySelection(cur);
4372                 } else
4373                         cell(cur.idx())->dispatch(cur, cmd);
4374                 break;
4375
4376         case LFUN_CLIPBOARD_PASTE:
4377         case LFUN_PRIMARY_SELECTION_PASTE: {
4378                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
4379                         theClipboard().getAsText(Clipboard::PlainTextType) :
4380                         theSelection().get();
4381                 if (clip.empty())
4382                         break;
4383                 // pass to InsertPlaintextString, but
4384                 // only if we have multi-cell content
4385                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
4386                         cur.recordUndoInset();
4387                         if (insertPlaintextString(cur.bv(), clip, false)) {
4388                                 // content has been replaced,
4389                                 // so cursor might be invalid
4390                                 cur.pos() = cur.lastpos();
4391                                 cur.pit() = cur.lastpit();
4392                                 bvcur.setCursor(cur);
4393                                 break;
4394                         }
4395                 }
4396                 // Let the cell handle normal text
4397                 cell(cur.idx())->dispatch(cur, cmd);
4398                 break;
4399         }
4400
4401         case LFUN_PASTE:
4402                 if (!tabularStackDirty()) {
4403                         if (!cur.selIsMultiCell())
4404                                 cell(cur.idx())->dispatch(cur, cmd);
4405                         break;
4406                 }
4407                 if (theClipboard().isInternal()) {
4408                         cur.recordUndoInset();
4409                         pasteClipboard(cur);
4410                 }
4411                 break;
4412
4413         case LFUN_FONT_EMPH:
4414         case LFUN_FONT_BOLD:
4415         case LFUN_FONT_BOLDSYMBOL:
4416         case LFUN_FONT_ROMAN:
4417         case LFUN_FONT_NOUN:
4418         case LFUN_FONT_ITAL:
4419         case LFUN_FONT_FRAK:
4420         case LFUN_FONT_TYPEWRITER:
4421         case LFUN_FONT_SANS:
4422         case LFUN_TEXTSTYLE_APPLY:
4423         case LFUN_TEXTSTYLE_UPDATE:
4424         case LFUN_FONT_SIZE:
4425         case LFUN_FONT_UNDERLINE:
4426         case LFUN_FONT_STRIKEOUT:
4427         case LFUN_FONT_UNDERUNDERLINE:
4428         case LFUN_FONT_UNDERWAVE:
4429         case LFUN_LANGUAGE:
4430         case LFUN_PARAGRAPH_PARAMS_APPLY:
4431         case LFUN_PARAGRAPH_PARAMS:
4432         case LFUN_WORD_CAPITALIZE:
4433         case LFUN_WORD_UPCASE:
4434         case LFUN_WORD_LOWCASE:
4435         case LFUN_CHARS_TRANSPOSE:
4436                 if (cur.selIsMultiCell()) {
4437                         row_type rs, re;
4438                         col_type cs, ce;
4439                         getSelection(cur, rs, re, cs, ce);
4440                         Cursor tmpcur = cur;
4441                         for (row_type r = rs; r <= re; ++r) {
4442                                 for (col_type c = cs; c <= ce; ++c) {
4443                                         // cursor follows cell:
4444                                         tmpcur.idx() = tabular.cellIndex(r, c);
4445                                         // select this cell only:
4446                                         tmpcur.pit() = 0;
4447                                         tmpcur.pos() = 0;
4448                                         tmpcur.resetAnchor();
4449                                         tmpcur.pit() = tmpcur.lastpit();
4450                                         tmpcur.pos() = tmpcur.top().lastpos();
4451                                         tmpcur.setCursor(tmpcur);
4452                                         tmpcur.setSelection();
4453                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
4454                                 }
4455                         }
4456                         break;
4457                 } else {
4458                         cell(cur.idx())->dispatch(cur, cmd);
4459                         break;
4460                 }
4461
4462         case LFUN_INSET_SETTINGS:
4463                 // relay this lfun to Inset, not to the cell.
4464                 Inset::doDispatch(cur, cmd);
4465                 break;
4466
4467         default:
4468                 // we try to handle this event in the insets dispatch function.
4469                 cell(cur.idx())->dispatch(cur, cmd);
4470                 break;
4471         }
4472 }
4473
4474
4475 // function sets an object as defined in func_status.h:
4476 // states OK, Unknown, Disabled, On, Off.
4477 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
4478         FuncStatus & status) const
4479 {
4480         switch (cmd.action()) {
4481         case LFUN_INSET_MODIFY: {
4482                 if (&cur.inset() != this || cmd.getArg(0) != "tabular")
4483                         break;
4484
4485                 // FIXME: We only check for the very first argument...
4486                 string const s = cmd.getArg(1);
4487                 // We always enable the lfun if it is coming from the dialog
4488                 // because the dialog makes sure all the settings are valid,
4489                 // even though the first argument might not be valid now.
4490                 if (s == "from-dialog") {
4491                         status.setEnabled(true);
4492                         return true;
4493                 }
4494
4495                 int action = Tabular::LAST_ACTION;
4496                 int i = 0;
4497                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4498                         if (tabularFeature[i].feature == s) {
4499                                 action = tabularFeature[i].action;
4500                                 break;
4501                         }
4502                 }
4503                 if (action == Tabular::LAST_ACTION) {
4504                         status.clear();
4505                         status.setUnknown(true);
4506                         return true;
4507                 }
4508
4509                 string const argument = cmd.getLongArg(2);
4510
4511                 row_type sel_row_start = 0;
4512                 row_type sel_row_end = 0;
4513                 col_type sel_col_start = 0;
4514                 col_type sel_col_end = 0;
4515                 Tabular::ltType dummyltt;
4516                 bool flag = true;
4517
4518                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4519
4520                 switch (action) {
4521                 case Tabular::SET_PWIDTH:
4522                 case Tabular::SET_MPWIDTH:
4523                 case Tabular::SET_SPECIAL_COLUMN:
4524                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4525                 case Tabular::APPEND_ROW:
4526                 case Tabular::APPEND_COLUMN:
4527                 case Tabular::DELETE_ROW:
4528                 case Tabular::DELETE_COLUMN:
4529                 case Tabular::COPY_ROW:
4530                 case Tabular::COPY_COLUMN:
4531                 case Tabular::SET_TOP_SPACE:
4532                 case Tabular::SET_BOTTOM_SPACE:
4533                 case Tabular::SET_INTERLINE_SPACE:
4534                         status.clear();
4535                         return true;
4536
4537                 case Tabular::SET_TABULAR_WIDTH:
4538                         status.setEnabled(!tabular.rotate &&  !tabular.is_long_tabular
4539                                 && tabular.tabular_valignment == Tabular::LYX_VALIGN_MIDDLE);
4540                         break;
4541
4542                 case Tabular::MOVE_COLUMN_RIGHT:
4543                 case Tabular::MOVE_COLUMN_LEFT:
4544                 case Tabular::MOVE_ROW_DOWN:
4545                 case Tabular::MOVE_ROW_UP: {
4546                         if (cur.selection()) {
4547                                 status.message(_("Selections not supported."));
4548                                 status.setEnabled(false);
4549                                 break;
4550                         }
4551
4552                         if ((action == Tabular::MOVE_COLUMN_RIGHT &&
4553                                 tabular.ncols() == tabular.cellColumn(cur.idx()) + 1) ||
4554                             (action == Tabular::MOVE_COLUMN_LEFT &&
4555                                 tabular.cellColumn(cur.idx()) == 0) ||
4556                             (action == Tabular::MOVE_ROW_DOWN &&
4557                                 tabular.nrows() == tabular.cellRow(cur.idx()) + 1) ||
4558                             (action == Tabular::MOVE_ROW_UP &&
4559                                 tabular.cellRow(cur.idx()) == 0)) {
4560                                         status.setEnabled(false);
4561                                         break;
4562                         }
4563
4564                         if (action == Tabular::MOVE_COLUMN_RIGHT ||
4565                             action == Tabular::MOVE_COLUMN_LEFT) {
4566                                 if (tabular.hasMultiColumn(tabular.cellColumn(cur.idx())) ||
4567                                     tabular.hasMultiColumn(tabular.cellColumn(cur.idx()) +
4568                                         (action == Tabular::MOVE_COLUMN_RIGHT ? 1 : -1))) {
4569                                         status.message(_("Multi-column in current or"
4570                                                          " destination column."));
4571                                         status.setEnabled(false);
4572                                         break;
4573                                 }
4574                         }
4575
4576                         if (action == Tabular::MOVE_ROW_DOWN ||
4577                             action == Tabular::MOVE_ROW_UP) {
4578                                 if (tabular.hasMultiRow(tabular.cellRow(cur.idx())) ||
4579                                     tabular.hasMultiRow(tabular.cellRow(cur.idx()) +
4580                                         (action == Tabular::MOVE_ROW_DOWN ? 1 : -1))) {
4581                                         status.message(_("Multi-row in current or"
4582                                                          " destination row."));
4583                                         status.setEnabled(false);
4584                                         break;
4585                                 }
4586                         }
4587
4588                         status.setEnabled(true);
4589                         break;
4590                 }
4591
4592                 case Tabular::SET_DECIMAL_POINT:
4593                         status.setEnabled(
4594                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
4595                         break;
4596
4597                 case Tabular::SET_MULTICOLUMN:
4598                 case Tabular::UNSET_MULTICOLUMN:
4599                 case Tabular::MULTICOLUMN:
4600                         // If a row is set as longtable caption, it must not be allowed
4601                         // to unset that this row is a multicolumn.
4602                         status.setEnabled(sel_row_start == sel_row_end
4603                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4604                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4605                         break;
4606
4607                 case Tabular::SET_MULTIROW:
4608                 case Tabular::UNSET_MULTIROW:
4609                 case Tabular::MULTIROW:
4610                         // If a row is set as longtable caption, it must not be allowed
4611                         // to unset that this row is a multirow.
4612                         status.setEnabled(sel_col_start == sel_col_end
4613                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4614                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4615                         break;
4616
4617                 case Tabular::SET_ALL_LINES:
4618                 case Tabular::UNSET_ALL_LINES:
4619                 case Tabular::SET_BORDER_LINES:
4620                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4621                         break;
4622
4623                 case Tabular::SET_LINE_TOP:
4624                 case Tabular::SET_LINE_BOTTOM:
4625                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4626                         break;
4627
4628                 case Tabular::SET_LINE_LEFT:
4629                 case Tabular::SET_LINE_RIGHT:
4630                         status.setEnabled(!tabular.use_booktabs
4631                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4632                         break;
4633
4634                 case Tabular::TOGGLE_LINE_TOP:
4635                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4636                         status.setOnOff(tabular.topLine(cur.idx()));
4637                         break;
4638
4639                 case Tabular::TOGGLE_LINE_BOTTOM:
4640                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4641                         status.setOnOff(tabular.bottomLine(cur.idx()));
4642                         break;
4643
4644                 case Tabular::TOGGLE_LINE_LEFT:
4645                         status.setEnabled(!tabular.use_booktabs
4646                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4647                         status.setOnOff(tabular.leftLine(cur.idx()));
4648                         break;
4649
4650                 case Tabular::TOGGLE_LINE_RIGHT:
4651                         status.setEnabled(!tabular.use_booktabs
4652                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4653                         status.setOnOff(tabular.rightLine(cur.idx()));
4654                         break;
4655
4656                 // multirow cells only inherit the alignment of the column if the column has
4657                 // no width, otherwise they are left-aligned
4658                 // therefore allow always left but right and center only if there is no width
4659                 case Tabular::M_ALIGN_LEFT:
4660                         flag = false;
4661                 case Tabular::ALIGN_LEFT:
4662                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4663                         break;
4664
4665                 case Tabular::M_ALIGN_RIGHT:
4666                         flag = false;
4667                 case Tabular::ALIGN_RIGHT:
4668                         status.setEnabled(!(tabular.isMultiRow(cur.idx())
4669                                 && !tabular.getPWidth(cur.idx()).zero()));
4670                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4671                         break;
4672
4673                 case Tabular::M_ALIGN_CENTER:
4674                         flag = false;
4675                 case Tabular::ALIGN_CENTER:
4676                         status.setEnabled(!(tabular.isMultiRow(cur.idx())
4677                                 && !tabular.getPWidth(cur.idx()).zero()));
4678                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4679                         break;
4680
4681                 case Tabular::ALIGN_BLOCK:
4682                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4683                                 && !tabular.isMultiRow(cur.idx()));
4684                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4685                         break;
4686
4687                 case Tabular::ALIGN_DECIMAL:
4688                         status.setEnabled(!tabular.isMultiRow(cur.idx())
4689                                 && !tabular.isMultiColumn(cur.idx()));
4690                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
4691                         break;
4692
4693                 case Tabular::M_VALIGN_TOP:
4694                         flag = false;
4695                 case Tabular::VALIGN_TOP:
4696                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4697                                 && !tabular.isMultiRow(cur.idx()));
4698                         status.setOnOff(
4699                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4700                         break;
4701
4702                 case Tabular::M_VALIGN_BOTTOM:
4703                         flag = false;
4704                 case Tabular::VALIGN_BOTTOM:
4705                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4706                                 && !tabular.isMultiRow(cur.idx()));
4707                         status.setOnOff(
4708                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4709                         break;
4710
4711                 case Tabular::M_VALIGN_MIDDLE:
4712                         flag = false;
4713                 case Tabular::VALIGN_MIDDLE:
4714                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4715                                 && !tabular.isMultiRow(cur.idx()));
4716                         status.setOnOff(
4717                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4718                         break;
4719
4720                 case Tabular::SET_LONGTABULAR:
4721                         // setting as longtable is not allowed when table is inside a float
4722                         if (cur.innerInsetOfType(FLOAT_CODE) != 0
4723                                 || cur.innerInsetOfType(WRAP_CODE) != 0)
4724                                 status.setEnabled(false);
4725                         else
4726                                 status.setEnabled(true);
4727                         status.setOnOff(tabular.is_long_tabular);
4728                         break;
4729
4730                 case Tabular::UNSET_LONGTABULAR:
4731                         status.setOnOff(!tabular.is_long_tabular);
4732                         break;
4733
4734                 case Tabular::TOGGLE_ROTATE_TABULAR:
4735                 case Tabular::SET_ROTATE_TABULAR:
4736                         status.setOnOff(tabular.rotate != 0);
4737                         break;
4738
4739                 case Tabular::TABULAR_VALIGN_TOP:
4740                         status.setEnabled(tabular.tabular_width.zero());
4741                         status.setOnOff(tabular.tabular_valignment
4742                                 == Tabular::LYX_VALIGN_TOP);
4743                         break;
4744                 case Tabular::TABULAR_VALIGN_MIDDLE:
4745                         status.setEnabled(tabular.tabular_width.zero());
4746                         status.setOnOff(tabular.tabular_valignment
4747                                 == Tabular::LYX_VALIGN_MIDDLE);
4748                         break;
4749                 case Tabular::TABULAR_VALIGN_BOTTOM:
4750                         status.setEnabled(tabular.tabular_width.zero());
4751                         status.setOnOff(tabular.tabular_valignment
4752                                 == Tabular::LYX_VALIGN_BOTTOM);
4753                         break;
4754
4755                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4756                         status.setOnOff(tabular.longtabular_alignment
4757                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4758                         break;
4759                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4760                         status.setOnOff(tabular.longtabular_alignment
4761                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4762                         break;
4763                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4764                         status.setOnOff(tabular.longtabular_alignment
4765                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4766                         break;
4767
4768                 case Tabular::UNSET_ROTATE_TABULAR:
4769                         status.setOnOff(tabular.rotate == 0);
4770                         break;
4771
4772                 case Tabular::TOGGLE_ROTATE_CELL:
4773                 case Tabular::SET_ROTATE_CELL:
4774                         status.setOnOff(!oneCellHasRotationState(false,
4775                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4776                         break;
4777
4778                 case Tabular::UNSET_ROTATE_CELL:
4779                         status.setOnOff(!oneCellHasRotationState(true,
4780                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4781                         break;
4782
4783                 case Tabular::SET_USEBOX:
4784                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4785                         break;
4786
4787                 // every row can only be one thing:
4788                 // either a footer or header
4789                 case Tabular::SET_LTFIRSTHEAD:
4790                         status.setEnabled(sel_row_start == sel_row_end);
4791                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4792                         break;
4793
4794                 case Tabular::UNSET_LTFIRSTHEAD:
4795                         status.setEnabled(sel_row_start == sel_row_end);
4796                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4797                         break;
4798
4799                 case Tabular::SET_LTHEAD:
4800                         status.setEnabled(sel_row_start == sel_row_end);
4801                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4802                         break;
4803
4804                 case Tabular::UNSET_LTHEAD:
4805                         status.setEnabled(sel_row_start == sel_row_end);
4806                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4807                         break;
4808
4809                 case Tabular::SET_LTFOOT:
4810                         status.setEnabled(sel_row_start == sel_row_end);
4811                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4812                         break;
4813
4814                 case Tabular::UNSET_LTFOOT:
4815                         status.setEnabled(sel_row_start == sel_row_end);
4816                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4817                         break;
4818
4819                 case Tabular::SET_LTLASTFOOT:
4820                         status.setEnabled(sel_row_start == sel_row_end);
4821                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4822                         break;
4823
4824                 case Tabular::UNSET_LTLASTFOOT:
4825                         status.setEnabled(sel_row_start == sel_row_end);
4826                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4827                         break;
4828
4829                 case Tabular::SET_LTNEWPAGE:
4830                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4831                         break;
4832                 case Tabular::UNSET_LTNEWPAGE:
4833                         status.setOnOff(!tabular.getLTNewPage(sel_row_start));
4834                         break;
4835
4836                 // only one row in head/firsthead/foot/lasthead can be the caption
4837                 // and a multirow cannot be set as caption
4838                 case Tabular::SET_LTCAPTION:
4839                         status.setEnabled(sel_row_start == sel_row_end
4840                                 && (!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4841                                  || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4842                                 && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4843                                  || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4844                                 && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4845                                  || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4846                                 && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4847                                  || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT))
4848                                 && !tabular.isMultiRow(sel_row_start));
4849                         status.setOnOff(tabular.ltCaption(sel_row_start));
4850                         break;
4851
4852                 case Tabular::UNSET_LTCAPTION:
4853                         status.setEnabled(sel_row_start == sel_row_end && tabular.ltCaption(sel_row_start));
4854                         break;
4855
4856                 case Tabular::TOGGLE_LTCAPTION:
4857                         status.setEnabled(sel_row_start == sel_row_end && (tabular.ltCaption(sel_row_start)
4858                                 || ((!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4859                                   || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4860                                  && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4861                                   || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4862                                  && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4863                                   || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4864                                  && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4865                                   || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT)))));
4866                         status.setOnOff(tabular.ltCaption(sel_row_start));
4867                         break;
4868
4869                 case Tabular::SET_BOOKTABS:
4870                         status.setOnOff(tabular.use_booktabs);
4871                         break;
4872
4873                 case Tabular::UNSET_BOOKTABS:
4874                         status.setOnOff(!tabular.use_booktabs);
4875                         break;
4876
4877                 default:
4878                         status.clear();
4879                         status.setEnabled(false);
4880                         break;
4881                 }
4882                 return true;
4883         }
4884
4885         case LFUN_CAPTION_INSERT: {
4886                 // caption is only allowed in caption cell of longtable
4887                 if (!tabular.ltCaption(tabular.cellRow(cur.idx()))) {
4888                         status.setEnabled(false);
4889                         return true;
4890                 }
4891                 // only standard caption is allowed
4892                 string arg = cmd.getArg(0);
4893                 if (!arg.empty() && arg != "Standard") {
4894                         status.setEnabled(false);
4895                         return true;
4896                 }
4897                 // check if there is already a caption
4898                 bool have_caption = false;
4899                 InsetTableCell itc = InsetTableCell(*tabular.cellInset(cur.idx()).get());
4900                 ParagraphList::const_iterator pit = itc.paragraphs().begin();
4901                 ParagraphList::const_iterator pend = itc.paragraphs().end();
4902                 for (; pit != pend; ++pit) {
4903                         InsetList::const_iterator it  = pit->insetList().begin();
4904                         InsetList::const_iterator end = pit->insetList().end();
4905                         for (; it != end; ++it) {
4906                                 if (it->inset->lyxCode() == CAPTION_CODE) {
4907                                         have_caption = true;
4908                                         break;
4909                                 }
4910                         }
4911                 }
4912                 status.setEnabled(!have_caption);
4913                 return true;
4914         }
4915
4916         // These are only enabled inside tabular
4917         case LFUN_CELL_BACKWARD:
4918         case LFUN_CELL_FORWARD:
4919                 status.setEnabled(true);
4920                 return true;
4921
4922         // disable these with multiple cells selected
4923         case LFUN_INSET_INSERT:
4924         case LFUN_TABULAR_INSERT:
4925         case LFUN_FLEX_INSERT:
4926         case LFUN_FLOAT_INSERT:
4927         case LFUN_FLOAT_WIDE_INSERT:
4928         case LFUN_FOOTNOTE_INSERT:
4929         case LFUN_MARGINALNOTE_INSERT:
4930         case LFUN_MATH_INSERT:
4931         case LFUN_MATH_MODE:
4932         case LFUN_MATH_MUTATE:
4933         case LFUN_MATH_DISPLAY:
4934         case LFUN_NOTE_INSERT:
4935         case LFUN_ARGUMENT_INSERT:
4936         case LFUN_BOX_INSERT:
4937         case LFUN_BRANCH_INSERT:
4938         case LFUN_PHANTOM_INSERT:
4939         case LFUN_WRAP_INSERT:
4940         case LFUN_PREVIEW_INSERT:
4941         case LFUN_ERT_INSERT: {
4942                 if (cur.selIsMultiCell()) {
4943                         status.setEnabled(false);
4944                         return true;
4945                 } else
4946                         return cell(cur.idx())->getStatus(cur, cmd, status);
4947         }
4948
4949         // disable in non-fixed-width cells
4950         case LFUN_PARAGRAPH_BREAK:
4951                 // multirow does not allow paragraph breaks
4952                 if (tabular.isMultiRow(cur.idx())) {
4953                         status.setEnabled(false);
4954                         return true;
4955                 }
4956                 // Fall back
4957         case LFUN_NEWLINE_INSERT: {
4958                 if (tabular.getPWidth(cur.idx()).zero()) {
4959                         status.setEnabled(false);
4960                         return true;
4961                 } else
4962                         return cell(cur.idx())->getStatus(cur, cmd, status);
4963         }
4964
4965         case LFUN_NEWPAGE_INSERT:
4966                 status.setEnabled(false);
4967                 return true;
4968
4969         case LFUN_PASTE:
4970                 if (tabularStackDirty() && theClipboard().isInternal()) {
4971                         if (cur.selIsMultiCell()) {
4972                                 row_type rs, re;
4973                                 col_type cs, ce;
4974                                 getSelection(cur, rs, re, cs, ce);
4975                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
4976                                           && paste_tabular->nrows() == re - rs + 1)
4977                                         status.setEnabled(true);
4978                                 else {
4979                                         status.setEnabled(false);
4980                                         status.message(_("Selection size should match clipboard content."));
4981                                 }
4982                         } else
4983                                 status.setEnabled(true);
4984                         return true;
4985                 }
4986                 return cell(cur.idx())->getStatus(cur, cmd, status);
4987
4988         case LFUN_INSET_SETTINGS:
4989                 // relay this lfun to Inset, not to the cell.
4990                 return Inset::getStatus(cur, cmd, status);
4991
4992         default:
4993                 // we try to handle this event in the insets dispatch function.
4994                 return cell(cur.idx())->getStatus(cur, cmd, status);
4995         }
4996         return false;
4997 }
4998
4999
5000 Inset::DisplayType InsetTabular::display() const
5001 {
5002                 if (tabular.is_long_tabular) {
5003                         switch (tabular.longtabular_alignment) {
5004                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
5005                                 return AlignLeft;
5006                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
5007                                 return AlignCenter;
5008                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
5009                                 return AlignRight;
5010                         default:
5011                                 return AlignCenter;
5012                         }
5013                 } else
5014                         return Inline;
5015 }
5016
5017
5018 void InsetTabular::latex(otexstream & os, OutputParams const & runparams) const
5019 {
5020         tabular.latex(os, runparams);
5021 }
5022
5023
5024 int InsetTabular::plaintext(odocstringstream & os,
5025         OutputParams const & runparams, size_t max_length) const
5026 {
5027         os << '\n'; // output table on a new line
5028         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
5029         tabular.plaintext(os, runparams, dp, false, 0, max_length);
5030         return PLAINTEXT_NEWLINE;
5031 }
5032
5033
5034 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
5035 {
5036         int ret = 0;
5037         Inset * master = 0;
5038
5039         // FIXME: Why not pass a proper DocIterator here?
5040 #if 0
5041         // if the table is inside a float it doesn't need the informaltable
5042         // wrapper. Search for it.
5043         for (master = owner(); master; master = master->owner())
5044                 if (master->lyxCode() == FLOAT_CODE)
5045                         break;
5046 #endif
5047
5048         if (!master) {
5049                 os << "<informaltable>";
5050                 ++ret;
5051         }
5052         ret += tabular.docbook(os, runparams);
5053         if (!master) {
5054                 os << "</informaltable>";
5055                 ++ret;
5056         }
5057         return ret;
5058 }
5059
5060
5061 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
5062 {
5063         return tabular.xhtml(xs, rp);
5064 }
5065
5066
5067 void InsetTabular::validate(LaTeXFeatures & features) const
5068 {
5069         tabular.validate(features);
5070         // FIXME XHTML
5071         // It'd be better to be able to get this from an InsetLayout, but at present
5072         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
5073         if (features.runparams().flavor == OutputParams::HTML)
5074                 features.addCSSSnippet(
5075                         "table { border: 1px solid black; display: inline-block; }\n"
5076                         "td { border: 1px solid black; padding: 0.5ex; }");
5077 }
5078
5079
5080 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
5081 {
5082         return tabular.cellInset(idx);
5083 }
5084
5085
5086 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
5087 {
5088         return tabular.cellInset(idx);
5089 }
5090
5091
5092 void InsetTabular::cursorPos(BufferView const & bv,
5093                 CursorSlice const & sl, bool boundary, int & x, int & y) const
5094 {
5095         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
5096
5097         // y offset     correction
5098         y += cellYPos(sl.idx());
5099         y += tabular.textVOffset(sl.idx());
5100         y += offset_valign_;
5101
5102         // x offset correction
5103         x += cellXPos(sl.idx());
5104         x += tabular.textHOffset(sl.idx());
5105         x += ADD_TO_TABULAR_WIDTH;
5106 }
5107
5108
5109 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
5110 {
5111         int xx = 0;
5112         int yy = 0;
5113         Inset const & inset = *tabular.cellInset(cell);
5114         Point o = bv.coordCache().getInsets().xy(&inset);
5115         int const xbeg = o.x_ - tabular.textHOffset(cell);
5116         int const xend = xbeg + tabular.cellWidth(cell);
5117         row_type const row = tabular.cellRow(cell);
5118         int const ybeg = o.y_ - tabular.rowAscent(row)
5119                 - tabular.interRowSpace(row) - tabular.textVOffset(cell);
5120         int const yend = ybeg + tabular.cellHeight(cell);
5121
5122         if (x < xbeg)
5123                 xx = xbeg - x;
5124         else if (x > xend)
5125                 xx = x - xend;
5126
5127         if (y < ybeg)
5128                 yy = ybeg - y;
5129         else if (y > yend)
5130                 yy = y - yend;
5131
5132         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
5133         //       << " ybeg=" << ybeg << " yend=" << yend
5134         //       << " xx=" << xx << " yy=" << yy
5135         //       << " dist=" << xx + yy << endl;
5136         return xx + yy;
5137 }
5138
5139
5140 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
5141 {
5142         //lyxerr << "InsetTabular::editXY: " << this << endl;
5143         cur.setSelection(false);
5144         cur.push(*this);
5145         cur.idx() = getNearestCell(cur.bv(), x, y);
5146         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
5147 }
5148
5149
5150 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
5151 {
5152         cur.idx() = getNearestCell(cur.bv(), x, y);
5153         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
5154 }
5155
5156
5157 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
5158 {
5159         idx_type idx_min = 0;
5160         int dist_min = numeric_limits<int>::max();
5161         for (idx_type i = 0, n = nargs(); i != n; ++i) {
5162                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
5163                         int const d = dist(bv, i, x, y);
5164                         if (d < dist_min) {
5165                                 dist_min = d;
5166                                 idx_min = i;
5167                         }
5168                 }
5169         }
5170         return idx_min;
5171 }
5172
5173
5174 int InsetTabular::cellYPos(idx_type const cell) const
5175 {
5176         row_type row = tabular.cellRow(cell);
5177         int ly = 0;
5178         for (row_type r = 0; r < row; ++r)
5179                 ly += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
5180                         + tabular.interRowSpace(r + 1);
5181         return ly;
5182 }
5183
5184
5185 int InsetTabular::cellXPos(idx_type const cell) const
5186 {
5187         col_type col = tabular.cellColumn(cell);
5188         int lx = 0;
5189         for (col_type c = 0; c < col; ++c)
5190                 lx += tabular.column_info[c].width;
5191         return lx;
5192 }
5193
5194
5195 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
5196 {
5197         row_type const row = tabular.cellRow(cur.idx());
5198         col_type const col = tabular.cellColumn(cur.idx());
5199
5200         if (isRightToLeft(cur)) {
5201                 if (tabular.cellColumn(cur.idx()) == 0) {
5202                         if (row == tabular.nrows() - 1)
5203                                 return;
5204                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
5205                 } else {
5206                         if (cur.idx() == 0)
5207                                 return;
5208                         if (col == 0)
5209                                 cur.idx() = tabular.getLastCellInRow(row - 1);
5210                         else
5211                                 cur.idx() = tabular.cellIndex(row, col - 1);
5212                 }
5213         } else {
5214                 if (tabular.isLastCell(cur.idx()))
5215                         return;
5216                 if (cur.idx() == tabular.getLastCellInRow(row))
5217                         cur.idx() = tabular.cellIndex(row + 1, 0);
5218                 else {
5219                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
5220                         cur.idx() = tabular.cellIndex(row, colnextcell);
5221                 }
5222         }
5223
5224         cur.boundary(false);
5225
5226         if (cur.selIsMultiCell()) {
5227                 cur.pit() = cur.lastpit();
5228                 cur.pos() = cur.lastpos();
5229                 return;
5230         }
5231
5232         cur.pit() = 0;
5233         cur.pos() = 0;
5234
5235         // in visual mode, place cursor at extreme left or right
5236
5237         switch(entry_from) {
5238
5239         case ENTRY_DIRECTION_RIGHT:
5240                 cur.posVisToRowExtremity(false /* !left */);
5241                 break;
5242         case ENTRY_DIRECTION_LEFT:
5243                 cur.posVisToRowExtremity(true /* left */);
5244                 break;
5245         case ENTRY_DIRECTION_IGNORE:
5246                 // nothing to do in this case
5247                 break;
5248
5249         }
5250         cur.setCurrentFont();
5251 }
5252
5253
5254 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
5255 {
5256         row_type const row = tabular.cellRow(cur.idx());
5257         col_type const col = tabular.cellColumn(cur.idx());
5258
5259         if (isRightToLeft(cur)) {
5260                 if (cur.idx() == tabular.getLastCellInRow(row)) {
5261                         if (row == 0)
5262                                 return;
5263                         cur.idx() = tabular.getFirstCellInRow(row);
5264                         cur.idx() = tabular.cellAbove(cur.idx());
5265                 } else {
5266                         if (tabular.isLastCell(cur.idx()))
5267                                 return;
5268                         if (cur.idx() == tabular.getLastCellInRow(row))
5269                                 cur.idx() = tabular.cellIndex(row + 1, 0);
5270                         else
5271                                 cur.idx() = tabular.cellIndex(row, col + 1);
5272                 }
5273         } else {
5274                 if (cur.idx() == 0) // first cell
5275                         return;
5276                 if (col == 0)
5277                         cur.idx() = tabular.getLastCellInRow(row - 1);
5278                 else
5279                         cur.idx() = tabular.cellIndex(row, col - 1);
5280         }
5281
5282         if (cur.selIsMultiCell()) {
5283                 cur.pit() = cur.lastpit();
5284                 cur.pos() = cur.lastpos();
5285                 return;
5286         }
5287
5288         cur.pit() = cur.lastpit();
5289         cur.pos() = cur.lastpos();
5290
5291         // in visual mode, place cursor at extreme left or right
5292
5293         switch(entry_from) {
5294
5295         case ENTRY_DIRECTION_RIGHT:
5296                 cur.posVisToRowExtremity(false /* !left */);
5297                 break;
5298         case ENTRY_DIRECTION_LEFT:
5299                 cur.posVisToRowExtremity(true /* left */);
5300                 break;
5301         case ENTRY_DIRECTION_IGNORE:
5302                 // nothing to do in this case
5303                 break;
5304
5305         }
5306         cur.setCurrentFont();
5307 }
5308
5309
5310 bool InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
5311 {
5312         istringstream is(argument);
5313         string s;
5314         is >> s;
5315         if (insetCode(s) != TABULAR_CODE)
5316                 return false;
5317
5318         // Safe guard.
5319         size_t safe_guard = 0;
5320         for (;;) {
5321                 if (is.eof())
5322                         break;
5323                 safe_guard++;
5324                 if (safe_guard > 1000) {
5325                         LYXERR0("parameter max count reached!");
5326                         break;
5327                 }
5328                 is >> s;
5329                 Tabular::Feature action = Tabular::LAST_ACTION;
5330
5331                 size_t i = 0;
5332                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
5333                         if (s != tabularFeature[i].feature)
5334                                 continue;
5335                         action = tabularFeature[i].action;
5336                         break;
5337                 }
5338                 if (action == Tabular::LAST_ACTION) {
5339                         LYXERR0("Feature not found " << s);
5340                         continue;
5341                 }
5342                 string val;
5343                 if (tabularFeature[i].need_value)
5344                         is >> val;
5345                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
5346                 tabularFeatures(cur, action, val);
5347         }
5348         return true;
5349 }
5350
5351
5352 static void checkLongtableSpecial(Tabular::ltType & ltt,
5353                           string const & special, bool & flag)
5354 {
5355         if (special == "dl_above") {
5356                 ltt.topDL = flag;
5357                 ltt.set = false;
5358         } else if (special == "dl_below") {
5359                 ltt.bottomDL = flag;
5360                 ltt.set = false;
5361         } else if (special == "empty") {
5362                 ltt.empty = flag;
5363                 ltt.set = false;
5364         } else if (flag) {
5365                 ltt.empty = false;
5366                 ltt.set = true;
5367         }
5368 }
5369
5370
5371 bool InsetTabular::oneCellHasRotationState(bool rotated,
5372                 row_type row_start, row_type row_end,
5373                 col_type col_start, col_type col_end) const
5374 {
5375         for (row_type r = row_start; r <= row_end; ++r)
5376                 for (col_type c = col_start; c <= col_end; ++c)
5377                         if (rotated) {
5378                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) != 0)
5379                                         return true;
5380                         } else {
5381                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) == 0)
5382                                         return true;
5383                         }
5384         return false;
5385 }
5386
5387
5388 void InsetTabular::tabularFeatures(Cursor & cur,
5389         Tabular::Feature feature, string const & value)
5390 {
5391         col_type sel_col_start;
5392         col_type sel_col_end;
5393         row_type sel_row_start;
5394         row_type sel_row_end;
5395         bool setLines = false;
5396         LyXAlignment setAlign = LYX_ALIGN_LEFT;
5397         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
5398
5399         switch (feature) {
5400
5401         case Tabular::M_ALIGN_LEFT:
5402         case Tabular::ALIGN_LEFT:
5403                 setAlign = LYX_ALIGN_LEFT;
5404                 break;
5405
5406         case Tabular::M_ALIGN_RIGHT:
5407         case Tabular::ALIGN_RIGHT:
5408                 setAlign = LYX_ALIGN_RIGHT;
5409                 break;
5410
5411         case Tabular::M_ALIGN_CENTER:
5412         case Tabular::ALIGN_CENTER:
5413                 setAlign = LYX_ALIGN_CENTER;
5414                 break;
5415
5416         case Tabular::ALIGN_BLOCK:
5417                 setAlign = LYX_ALIGN_BLOCK;
5418                 break;
5419
5420         case Tabular::ALIGN_DECIMAL:
5421                 setAlign = LYX_ALIGN_DECIMAL;
5422                 break;
5423
5424         case Tabular::M_VALIGN_TOP:
5425         case Tabular::VALIGN_TOP:
5426                 setVAlign = Tabular::LYX_VALIGN_TOP;
5427                 break;
5428
5429         case Tabular::M_VALIGN_BOTTOM:
5430         case Tabular::VALIGN_BOTTOM:
5431                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
5432                 break;
5433
5434         case Tabular::M_VALIGN_MIDDLE:
5435         case Tabular::VALIGN_MIDDLE:
5436                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
5437                 break;
5438
5439         default:
5440                 break;
5441         }
5442
5443         cur.recordUndoInset(this);
5444
5445         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5446         row_type const row = tabular.cellRow(cur.idx());
5447         col_type const column = tabular.cellColumn(cur.idx());
5448         bool flag = true;
5449         Tabular::ltType ltt;
5450
5451         switch (feature) {
5452
5453         case Tabular::SET_TABULAR_WIDTH:
5454                 tabular.setTabularWidth(Length(value));
5455                 break;
5456
5457         case Tabular::SET_PWIDTH: {
5458                 Length const len(value);
5459                 tabular.setColumnPWidth(cur, cur.idx(), len);
5460                 if (len.zero()
5461                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
5462                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
5463                 break;
5464         }
5465
5466         case Tabular::SET_MPWIDTH:
5467                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
5468                 break;
5469
5470         case Tabular::SET_MROFFSET:
5471                 tabular.setMROffset(cur, cur.idx(), Length(value));
5472                 break;
5473
5474         case Tabular::SET_SPECIAL_COLUMN:
5475         case Tabular::SET_SPECIAL_MULTICOLUMN:
5476                 if (value == "none")
5477                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
5478                 else
5479                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
5480                 break;
5481
5482         case Tabular::APPEND_ROW:
5483                 // append the row into the tabular
5484                 tabular.appendRow(row);
5485                 break;
5486
5487         case Tabular::APPEND_COLUMN:
5488                 // append the column into the tabular
5489                 tabular.appendColumn(column);
5490                 cur.idx() = tabular.cellIndex(row, column);
5491                 break;
5492
5493         case Tabular::DELETE_ROW:
5494                 if (sel_row_end == tabular.nrows() - 1 && sel_row_start != 0) {
5495                         for (col_type c = 0; c < tabular.ncols(); c++)
5496                                 tabular.setBottomLine(tabular.cellIndex(sel_row_start - 1, c),
5497                                         tabular.bottomLine(tabular.cellIndex(sel_row_end, c)));
5498                 }
5499
5500                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5501                         tabular.deleteRow(sel_row_start);
5502                 if (sel_row_start >= tabular.nrows())
5503                         --sel_row_start;
5504                 cur.idx() = tabular.cellIndex(sel_row_start, column);
5505                 cur.pit() = 0;
5506                 cur.pos() = 0;
5507                 cur.setSelection(false);
5508                 break;
5509
5510         case Tabular::DELETE_COLUMN:
5511                 if (sel_col_end == tabular.ncols() - 1 && sel_col_start != 0) {
5512                         for (row_type r = 0; r < tabular.nrows(); r++)
5513                                 tabular.setRightLine(tabular.cellIndex(r, sel_col_start - 1),
5514                                         tabular.rightLine(tabular.cellIndex(r, sel_col_end)));
5515                 }
5516
5517                 if (sel_col_start == 0 && sel_col_end != tabular.ncols() - 1) {
5518                         for (row_type r = 0; r < tabular.nrows(); r++)
5519                                 tabular.setLeftLine(tabular.cellIndex(r, sel_col_end + 1),
5520                                         tabular.leftLine(tabular.cellIndex(r, 0)));
5521                 }
5522
5523                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5524                         tabular.deleteColumn(sel_col_start);
5525                 if (sel_col_start >= tabular.ncols())
5526                         --sel_col_start;
5527                 cur.idx() = tabular.cellIndex(row, sel_col_start);
5528                 cur.pit() = 0;
5529                 cur.pos() = 0;
5530                 cur.setSelection(false);
5531                 break;
5532
5533         case Tabular::COPY_ROW:
5534                 tabular.copyRow(row);
5535                 break;
5536
5537         case Tabular::COPY_COLUMN:
5538                 tabular.copyColumn(column);
5539                 cur.idx() = tabular.cellIndex(row, column);
5540                 break;
5541
5542         case Tabular::MOVE_COLUMN_RIGHT:
5543                 tabular.moveColumn(column, Tabular::RIGHT);
5544                 cur.idx() = tabular.cellIndex(row, column + 1);
5545                 break;
5546
5547         case Tabular::MOVE_COLUMN_LEFT:
5548                 tabular.moveColumn(column, Tabular::LEFT);
5549                 cur.idx() = tabular.cellIndex(row, column - 1);
5550                 break;
5551
5552         case Tabular::MOVE_ROW_DOWN:
5553                 tabular.moveRow(row, Tabular::DOWN);
5554                 cur.idx() = tabular.cellIndex(row + 1, column);
5555                 break;
5556
5557         case Tabular::MOVE_ROW_UP:
5558                 tabular.moveRow(row, Tabular::UP);
5559                 cur.idx() = tabular.cellIndex(row - 1, column);
5560                 break;
5561
5562         case Tabular::SET_LINE_TOP:
5563         case Tabular::TOGGLE_LINE_TOP: {
5564                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
5565                                ? (value == "true") : !tabular.topLine(cur.idx());
5566                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5567                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5568                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
5569                 break;
5570         }
5571
5572         case Tabular::SET_LINE_BOTTOM:
5573         case Tabular::TOGGLE_LINE_BOTTOM: {
5574                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
5575                                ? (value == "true") : !tabular.bottomLine(cur.idx());
5576                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5577                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5578                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
5579                 break;
5580         }
5581
5582         case Tabular::SET_LINE_LEFT:
5583         case Tabular::TOGGLE_LINE_LEFT: {
5584                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
5585                                ? (value == "true") : !tabular.leftLine(cur.idx());
5586                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5587                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5588                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
5589                 break;
5590         }
5591
5592         case Tabular::SET_LINE_RIGHT:
5593         case Tabular::TOGGLE_LINE_RIGHT: {
5594                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
5595                                ? (value == "true") : !tabular.rightLine(cur.idx());
5596                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5597                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5598                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
5599                 break;
5600         }
5601
5602         case Tabular::M_ALIGN_LEFT:
5603         case Tabular::M_ALIGN_RIGHT:
5604         case Tabular::M_ALIGN_CENTER:
5605         case Tabular::ALIGN_LEFT:
5606         case Tabular::ALIGN_RIGHT:
5607         case Tabular::ALIGN_CENTER:
5608         case Tabular::ALIGN_BLOCK:
5609         case Tabular::ALIGN_DECIMAL:
5610                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5611                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5612                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign,
5613                                 !tabular.getPWidth(c).zero());
5614                 break;
5615
5616         case Tabular::M_VALIGN_TOP:
5617         case Tabular::M_VALIGN_BOTTOM:
5618         case Tabular::M_VALIGN_MIDDLE:
5619                 flag = false;
5620         case Tabular::VALIGN_TOP:
5621         case Tabular::VALIGN_BOTTOM:
5622         case Tabular::VALIGN_MIDDLE:
5623                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5624                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5625                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
5626                 break;
5627
5628         case Tabular::SET_MULTICOLUMN: {
5629                 if (!cur.selection()) {
5630                         // just multicol for one single cell
5631                         // check whether we are completely in a multicol
5632                         if (!tabular.isMultiColumn(cur.idx()))
5633                                 tabular.setMultiColumn(cur.idx(), 1,
5634                                         tabular.rightLine(cur.idx()));
5635                         break;
5636                 }
5637                 // we have a selection so this means we just add all these
5638                 // cells to form a multicolumn cell
5639                 idx_type const s_start = cur.selBegin().idx();
5640                 row_type const col_start = tabular.cellColumn(s_start);
5641                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
5642                 cur.idx() = tabular.setMultiColumn(s_start, col_end - col_start + 1,
5643                                                    tabular.rightLine(cur.selEnd().idx()));
5644                 cur.pit() = 0;
5645                 cur.pos() = 0;
5646                 cur.setSelection(false);
5647                 break;
5648         }
5649
5650         case Tabular::UNSET_MULTICOLUMN: {
5651                 if (!cur.selection()) {
5652                         if (tabular.isMultiColumn(cur.idx()))
5653                                 tabular.unsetMultiColumn(cur.idx());
5654                 }
5655                 break;
5656         }
5657
5658         case Tabular::MULTICOLUMN: {
5659                 if (!cur.selection()) {
5660                         if (tabular.isMultiColumn(cur.idx()))
5661                                 tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5662                         else
5663                                 tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5664                         break;
5665                 }
5666                 bool merge = false;
5667                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5668                         row_type const r = sel_row_start;
5669                         if (!tabular.isMultiColumn(tabular.cellIndex(r, c))
5670                             || (r > sel_row_start && !tabular.isPartOfMultiColumn(r, c)))
5671                                 merge = true;
5672                 }
5673                 // If the selection contains at least one singlecol cell
5674                 // or multiple multicol cells,
5675                 // we assume the user will merge is to a single multicol
5676                 if (merge)
5677                         tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5678                 else
5679                         tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5680                 break;
5681         }
5682
5683         case Tabular::SET_MULTIROW: {
5684                 if (!cur.selection()) {
5685                         // just multirow for one single cell
5686                         // check whether we are completely in a multirow
5687                         if (!tabular.isMultiRow(cur.idx()))
5688                                 tabular.setMultiRow(cur.idx(), 1,
5689                                                     tabular.bottomLine(cur.idx()),
5690                                                     tabular.getAlignment(cur.idx()));
5691                         break;
5692                 }
5693                 // we have a selection so this means we just add all this
5694                 // cells to form a multirow cell
5695                 idx_type const s_start = cur.selBegin().idx();
5696                 row_type const row_start = tabular.cellRow(s_start);
5697                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5698                 cur.idx() = tabular.setMultiRow(s_start, row_end - row_start + 1,
5699                                                 tabular.bottomLine(cur.selEnd().idx()),
5700                                                 tabular.getAlignment(cur.selEnd().idx()));
5701                 cur.pit() = 0;
5702                 cur.pos() = 0;
5703                 cur.setSelection(false);
5704                 break;
5705         }
5706
5707         case Tabular::UNSET_MULTIROW: {
5708                 if (!cur.selection()) {
5709                         if (tabular.isMultiRow(cur.idx()))
5710                                 tabular.unsetMultiRow(cur.idx());
5711                 }
5712                 break;
5713         }
5714
5715         case Tabular::MULTIROW: {
5716                 if (!cur.selection()) {
5717                         if (tabular.isMultiRow(cur.idx()))
5718                                 tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5719                         else
5720                                 tabularFeatures(cur, Tabular::SET_MULTIROW);
5721                         break;
5722                 }
5723                 bool merge = false;
5724                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5725                         col_type const c = sel_col_start;
5726                         if (!tabular.isMultiRow(tabular.cellIndex(r, c))
5727                             || (r > sel_row_start && !tabular.isPartOfMultiRow(r, c)))
5728                                 merge = true;
5729                 }
5730                 // If the selection contains at least one singlerow cell
5731                 // or multiple multirow cells,
5732                 // we assume the user will merge is to a single multirow
5733                 if (merge)
5734                         tabularFeatures(cur, Tabular::SET_MULTIROW);
5735                 else
5736                         tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5737                 break;
5738         }
5739
5740         case Tabular::SET_ALL_LINES:
5741                 setLines = true;
5742         case Tabular::UNSET_ALL_LINES:
5743                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5744                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5745                                 idx_type const cell = tabular.cellIndex(r, c);
5746                                 tabular.setTopLine(cell, setLines);
5747                                 tabular.setBottomLine(cell, setLines);
5748                                 tabular.setRightLine(cell, setLines);
5749                                 tabular.setLeftLine(cell, setLines);
5750                         }
5751                 break;
5752
5753         case Tabular::SET_BORDER_LINES:
5754                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5755                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
5756                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
5757                 }
5758                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5759                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
5760                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
5761                 }
5762                 break;
5763
5764         case Tabular::SET_LONGTABULAR:
5765                 tabular.is_long_tabular = true;
5766                 break;
5767
5768         case Tabular::UNSET_LONGTABULAR:
5769                 for (row_type r = 0; r < tabular.nrows(); ++r) {
5770                         if (tabular.ltCaption(r)) {
5771                                 cur.idx() = tabular.cellIndex(r, 0);
5772                                 cur.pit() = 0;
5773                                 cur.pos() = 0;
5774                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5775                         }
5776                 }
5777                 tabular.is_long_tabular = false;
5778                 break;
5779
5780         case Tabular::SET_ROTATE_TABULAR:
5781                 tabular.rotate = convert<int>(value);
5782                 break;
5783
5784         case Tabular::UNSET_ROTATE_TABULAR:
5785                 tabular.rotate = 0;
5786                 break;
5787
5788         case Tabular::TOGGLE_ROTATE_TABULAR:
5789                 // when pressing the rotate button we default to 90° rotation
5790                 tabular.rotate != 0 ? tabular.rotate = 0 : tabular.rotate = 90;
5791                 break;
5792
5793         case Tabular::TABULAR_VALIGN_TOP:
5794                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5795                 break;
5796
5797         case Tabular::TABULAR_VALIGN_MIDDLE:
5798                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5799                 break;
5800
5801         case Tabular::TABULAR_VALIGN_BOTTOM:
5802                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5803                 break;
5804
5805         case Tabular::LONGTABULAR_ALIGN_LEFT:
5806                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5807                 break;
5808
5809         case Tabular::LONGTABULAR_ALIGN_CENTER:
5810                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5811                 break;
5812
5813         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5814                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5815                 break;
5816
5817
5818
5819         case Tabular::SET_ROTATE_CELL:
5820                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5821                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5822                                 tabular.setRotateCell(tabular.cellIndex(r, c), convert<int>(value));
5823                 break;
5824
5825         case Tabular::UNSET_ROTATE_CELL:
5826                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5827                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5828                                 tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5829                 break;
5830
5831         case Tabular::TOGGLE_ROTATE_CELL:
5832                 {
5833                 bool oneNotRotated = oneCellHasRotationState(false,
5834                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5835
5836                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5837                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5838                                 // when pressing the rotate cell button we default to 90° rotation
5839                                 if (oneNotRotated)
5840                                         tabular.setRotateCell(tabular.cellIndex(r, c), 90);
5841                                 else
5842                                         tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5843                         }
5844                 }
5845                 break;
5846
5847         case Tabular::SET_USEBOX: {
5848                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5849                 if (val == tabular.getUsebox(cur.idx()))
5850                         val = Tabular::BOX_NONE;
5851                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5852                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5853                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
5854                 break;
5855         }
5856
5857         case Tabular::UNSET_LTFIRSTHEAD:
5858                 flag = false;
5859         case Tabular::SET_LTFIRSTHEAD:
5860                 tabular.getRowOfLTFirstHead(row, ltt);
5861                 checkLongtableSpecial(ltt, value, flag);
5862                 tabular.setLTHead(row, flag, ltt, true);
5863                 break;
5864
5865         case Tabular::UNSET_LTHEAD:
5866                 flag = false;
5867         case Tabular::SET_LTHEAD:
5868                 tabular.getRowOfLTHead(row, ltt);
5869                 checkLongtableSpecial(ltt, value, flag);
5870                 tabular.setLTHead(row, flag, ltt, false);
5871                 break;
5872
5873         case Tabular::UNSET_LTFOOT:
5874                 flag = false;
5875         case Tabular::SET_LTFOOT:
5876                 tabular.getRowOfLTFoot(row, ltt);
5877                 checkLongtableSpecial(ltt, value, flag);
5878                 tabular.setLTFoot(row, flag, ltt, false);
5879                 break;
5880
5881         case Tabular::UNSET_LTLASTFOOT:
5882                 flag = false;
5883         case Tabular::SET_LTLASTFOOT:
5884                 tabular.getRowOfLTLastFoot(row, ltt);
5885                 checkLongtableSpecial(ltt, value, flag);
5886                 tabular.setLTFoot(row, flag, ltt, true);
5887                 break;
5888
5889         case Tabular::UNSET_LTNEWPAGE:
5890                 flag = false;
5891         case Tabular::SET_LTNEWPAGE:
5892                 tabular.setLTNewPage(row, flag);
5893                 break;
5894
5895         case Tabular::SET_LTCAPTION: {
5896                 if (tabular.ltCaption(row))
5897                         break;
5898                 cur.idx() = tabular.setLTCaption(row, true);
5899                 cur.pit() = 0;
5900                 cur.pos() = 0;
5901                 cur.setSelection(false);
5902                 // If a row is set as caption, then also insert
5903                 // a caption. Otherwise the LaTeX output is broken.
5904                 // Select cell if it is non-empty
5905                 if (cur.lastpos() > 0 || cur.lastpit() > 0)
5906                         lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
5907                 lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
5908                 break;
5909         }
5910
5911         case Tabular::UNSET_LTCAPTION: {
5912                 if (!tabular.ltCaption(row))
5913                         break;
5914                 cur.idx() = tabular.setLTCaption(row, false);
5915                 cur.pit() = 0;
5916                 cur.pos() = 0;
5917                 cur.setSelection(false);
5918                 FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
5919                 if (lyx::getStatus(fr).enabled())
5920                         lyx::dispatch(fr);
5921                 break;
5922         }
5923
5924         case Tabular::TOGGLE_LTCAPTION: {
5925                 if (tabular.ltCaption(row))
5926                         tabularFeatures(cur, Tabular::UNSET_LTCAPTION);
5927                 else
5928                         tabularFeatures(cur, Tabular::SET_LTCAPTION);
5929                 break;
5930         }
5931
5932         case Tabular::SET_BOOKTABS:
5933                 tabular.use_booktabs = true;
5934                 break;
5935
5936         case Tabular::UNSET_BOOKTABS:
5937                 tabular.use_booktabs = false;
5938                 break;
5939
5940         case Tabular::SET_TOP_SPACE: {
5941                 Length len;
5942                 if (value == "default")
5943                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5944                                 tabular.row_info[r].top_space_default = true;
5945                 else if (value == "none")
5946                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5947                                 tabular.row_info[r].top_space_default = false;
5948                                 tabular.row_info[r].top_space = len;
5949                         }
5950                 else if (isValidLength(value, &len))
5951                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5952                                 tabular.row_info[r].top_space_default = false;
5953                                 tabular.row_info[r].top_space = len;
5954                         }
5955                 break;
5956         }
5957
5958         case Tabular::SET_BOTTOM_SPACE: {
5959                 Length len;
5960                 if (value == "default")
5961                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5962                                 tabular.row_info[r].bottom_space_default = true;
5963                 else if (value == "none")
5964                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5965                                 tabular.row_info[r].bottom_space_default = false;
5966                                 tabular.row_info[r].bottom_space = len;
5967                         }
5968                 else if (isValidLength(value, &len))
5969                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5970                                 tabular.row_info[r].bottom_space_default = false;
5971                                 tabular.row_info[r].bottom_space = len;
5972                         }
5973                 break;
5974         }
5975
5976         case Tabular::SET_INTERLINE_SPACE: {
5977                 Length len;
5978                 if (value == "default")
5979                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5980                                 tabular.row_info[r].interline_space_default = true;
5981                 else if (value == "none")
5982                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5983                                 tabular.row_info[r].interline_space_default = false;
5984                                 tabular.row_info[r].interline_space = len;
5985                         }
5986                 else if (isValidLength(value, &len))
5987                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5988                                 tabular.row_info[r].interline_space_default = false;
5989                                 tabular.row_info[r].interline_space = len;
5990                         }
5991                 break;
5992         }
5993
5994         case Tabular::SET_DECIMAL_POINT:
5995                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5996                         tabular.column_info[c].decimal_point = from_utf8(value);
5997                 break;
5998
5999         // dummy stuff just to avoid warnings
6000         case Tabular::LAST_ACTION:
6001                 break;
6002         }
6003 }
6004
6005
6006 bool InsetTabular::copySelection(Cursor & cur)
6007 {
6008         if (!cur.selection())
6009                 return false;
6010
6011         row_type rs, re;
6012         col_type cs, ce;
6013         getSelection(cur, rs, re, cs, ce);
6014
6015         paste_tabular.reset(new Tabular(tabular));
6016
6017         for (row_type r = 0; r < rs; ++r)
6018                 paste_tabular->deleteRow(0);
6019
6020         row_type const rows = re - rs + 1;
6021         while (paste_tabular->nrows() > rows)
6022                 paste_tabular->deleteRow(rows);
6023
6024         for (col_type c = 0; c < cs; ++c)
6025                 paste_tabular->deleteColumn(0);
6026
6027         col_type const columns = ce - cs + 1;
6028         while (paste_tabular->ncols() > columns)
6029                 paste_tabular->deleteColumn(columns);
6030
6031         paste_tabular->setBuffer(tabular.buffer());
6032
6033         odocstringstream os;
6034         OutputParams const runparams(0);
6035         paste_tabular->plaintext(os, runparams, 0, true, '\t', INT_MAX);
6036         // Needed for the "Edit->Paste recent" menu and the system clipboard.
6037         cap::copySelection(cur, os.str());
6038
6039         // mark tabular stack dirty
6040         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
6041         // when we (hopefully) have a one-for-all paste mechanism.
6042         // This must be called after cap::copySelection.
6043         dirtyTabularStack(true);
6044
6045         return true;
6046 }
6047
6048
6049 bool InsetTabular::pasteClipboard(Cursor & cur)
6050 {
6051         if (!paste_tabular)
6052                 return false;
6053         col_type actcol = tabular.cellColumn(cur.idx());
6054         row_type actrow = tabular.cellRow(cur.idx());
6055
6056         if (cur.selIsMultiCell()) {
6057                 row_type re;
6058                 col_type ce;
6059                 getSelection(cur, actrow, re, actcol, ce);
6060         }
6061
6062         for (row_type r1 = 0, r2 = actrow;
6063              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
6064              ++r1, ++r2) {
6065                 for (col_type c1 = 0, c2 = actcol;
6066                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
6067                     ++c1, ++c2) {
6068                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
6069                               tabular.isPartOfMultiColumn(r2, c2))
6070                                 continue;
6071                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
6072                                 --c2;
6073                                 continue;
6074                         }
6075                         if (tabular.isPartOfMultiColumn(r2, c2)) {
6076                                 --c1;
6077                                 continue;
6078                         }
6079                         shared_ptr<InsetTableCell> inset(
6080                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
6081                         tabular.setCellInset(r2, c2, inset);
6082                         // FIXME?: why do we need to do this explicitly? (EL)
6083                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
6084
6085                         // FIXME: change tracking (MG)
6086                         inset->setChange(Change(buffer().params().track_changes ?
6087                                                 Change::INSERTED : Change::UNCHANGED));
6088                         cur.pos() = 0;
6089                 }
6090         }
6091         return true;
6092 }
6093
6094
6095 void InsetTabular::cutSelection(Cursor & cur)
6096 {
6097         if (!cur.selection())
6098                 return;
6099
6100         row_type rs, re;
6101         col_type cs, ce;
6102         getSelection(cur, rs, re, cs, ce);
6103         for (row_type r = rs; r <= re; ++r) {
6104                 for (col_type c = cs; c <= ce; ++c) {
6105                         shared_ptr<InsetTableCell> t
6106                                 = cell(tabular.cellIndex(r, c));
6107                         if (buffer().params().track_changes)
6108                                 // FIXME: Change tracking (MG)
6109                                 t->setChange(Change(Change::DELETED));
6110                         else
6111                                 t->clear();
6112                 }
6113         }
6114
6115         // cursor position might be invalid now
6116         if (cur.pit() > cur.lastpit())
6117                 cur.pit() = cur.lastpit();
6118         if (cur.pos() > cur.lastpos())
6119                 cur.pos() = cur.lastpos();
6120         cur.clearSelection();
6121 }
6122
6123
6124 bool InsetTabular::isRightToLeft(Cursor & cur) const
6125 {
6126         // LASSERT: It might be better to abandon this Buffer.
6127         LASSERT(cur.depth() > 1, return false);
6128         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
6129         pos_type const parentpos = cur[cur.depth() - 2].pos();
6130         return parentpar.getFontSettings(buffer().params(),
6131                                          parentpos).language()->rightToLeft();
6132 }
6133
6134
6135 docstring InsetTabular::asString(idx_type stidx, idx_type enidx,
6136                                  bool intoInsets)
6137 {
6138         LASSERT(stidx <= enidx, return docstring());
6139         docstring retval;
6140         col_type const col1 = tabular.cellColumn(stidx);
6141         col_type const col2 = tabular.cellColumn(enidx);
6142         row_type const row1 = tabular.cellRow(stidx);
6143         row_type const row2 = tabular.cellRow(enidx);
6144         bool first = true;
6145         for (col_type col = col1; col <= col2; col++)
6146                 for (row_type row = row1; row <= row2; row++) {
6147                         if (!first)
6148                                 retval += "\n";
6149                         else
6150                                 first = false;
6151                         retval += tabular.cellInset(row, col)->asString(intoInsets);
6152                 }
6153         return retval;
6154 }
6155
6156
6157 void InsetTabular::getSelection(Cursor & cur,
6158         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
6159 {
6160         CursorSlice const & beg = cur.selBegin();
6161         CursorSlice const & end = cur.selEnd();
6162         cs = tabular.cellColumn(beg.idx());
6163         ce = tabular.cellColumn(end.idx());
6164         if (cs > ce)
6165                 swap(cs, ce);
6166
6167         rs = tabular.cellRow(beg.idx());
6168         re = tabular.cellRow(end.idx());
6169         if (rs > re)
6170                 swap(rs, re);
6171 }
6172
6173
6174 Text * InsetTabular::getText(int idx) const
6175 {
6176         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
6177 }
6178
6179
6180 void InsetTabular::setChange(Change const & change)
6181 {
6182         for (idx_type idx = 0; idx < nargs(); ++idx)
6183                 cell(idx)->setChange(change);
6184 }
6185
6186
6187 void InsetTabular::acceptChanges()
6188 {
6189         for (idx_type idx = 0; idx < nargs(); ++idx)
6190                 cell(idx)->acceptChanges();
6191 }
6192
6193
6194 void InsetTabular::rejectChanges()
6195 {
6196         for (idx_type idx = 0; idx < nargs(); ++idx)
6197                 cell(idx)->rejectChanges();
6198 }
6199
6200
6201 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
6202 {
6203         return tabular.getPWidth(cell).zero();
6204 }
6205
6206
6207 bool InsetTabular::forcePlainLayout(idx_type cell) const
6208 {
6209         return !tabular.getPWidth(cell).zero();
6210 }
6211
6212
6213 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
6214                                      bool usePaste)
6215 {
6216         if (buf.length() <= 0)
6217                 return true;
6218
6219         col_type cols = 1;
6220         row_type rows = 1;
6221         col_type maxCols = 1;
6222         size_t const len = buf.length();
6223         size_t p = 0;
6224
6225         while (p < len &&
6226                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
6227                 switch (buf[p]) {
6228                 case '\t':
6229                         ++cols;
6230                         break;
6231                 case '\n':
6232                         if (p + 1 < len)
6233                                 ++rows;
6234                         maxCols = max(cols, maxCols);
6235                         cols = 1;
6236                         break;
6237                 }
6238                 ++p;
6239         }
6240         maxCols = max(cols, maxCols);
6241         Tabular * loctab;
6242         idx_type cell = 0;
6243         col_type ocol = 0;
6244         row_type row = 0;
6245         if (usePaste) {
6246                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
6247                 loctab = paste_tabular.get();
6248                 dirtyTabularStack(true);
6249         } else {
6250                 loctab = &tabular;
6251                 cell = bv.cursor().idx();
6252                 ocol = tabular.cellColumn(cell);
6253                 row = tabular.cellRow(cell);
6254         }
6255
6256         size_t op = 0;
6257         idx_type const cells = loctab->numberofcells;
6258         p = 0;
6259         cols = ocol;
6260         rows = loctab->nrows();
6261         col_type const columns = loctab->ncols();
6262
6263         while (cell < cells && p < len && row < rows &&
6264                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
6265         {
6266                 if (p >= len)
6267                         break;
6268                 switch (buf[p]) {
6269                 case '\t':
6270                         // we can only set this if we are not too far right
6271                         if (cols < columns) {
6272                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6273                                 Font const font = bv.textMetrics(&inset->text()).
6274                                         displayFont(0, 0);
6275                                 inset->setText(buf.substr(op, p - op), font,
6276                                                buffer().params().track_changes);
6277                                 ++cols;
6278                                 ++cell;
6279                         }
6280                         break;
6281                 case '\n':
6282                         // we can only set this if we are not too far right
6283                         if (cols < columns) {
6284                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
6285                                 Font const font = bv.textMetrics(&inset->text()).
6286                                         displayFont(0, 0);
6287                                 inset->setText(buf.substr(op, p - op), font,
6288                                                buffer().params().track_changes);
6289                         }
6290                         cols = ocol;
6291                         ++row;
6292                         if (row < rows)
6293                                 cell = loctab->cellIndex(row, cols);
6294                         break;
6295                 }
6296                 ++p;
6297                 op = p;
6298         }
6299         // check for the last cell if there is no trailing '\n'
6300         if (cell < cells && op < len) {
6301                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6302                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
6303                 inset->setText(buf.substr(op, len - op), font,
6304                         buffer().params().track_changes);
6305         }
6306         return true;
6307 }
6308
6309
6310 void InsetTabular::addPreview(DocIterator const & inset_pos,
6311         PreviewLoader & loader) const
6312 {
6313         DocIterator cell_pos = inset_pos;
6314
6315         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
6316         for (row_type r = 0; r < tabular.nrows(); ++r) {
6317                 for (col_type c = 0; c < tabular.ncols(); ++c) {
6318                         cell_pos.top().idx() = tabular.cellIndex(r, c);
6319                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
6320                 }
6321         }
6322 }
6323
6324
6325 bool InsetTabular::completionSupported(Cursor const & cur) const
6326 {
6327         Cursor const & bvCur = cur.bv().cursor();
6328         if (&bvCur.inset() != this)
6329                 return false;
6330         return cur.text()->completionSupported(cur);
6331 }
6332
6333
6334 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
6335 {
6336         return completionSupported(cur);
6337 }
6338
6339
6340 bool InsetTabular::automaticInlineCompletion() const
6341 {
6342         return lyxrc.completion_inline_text;
6343 }
6344
6345
6346 bool InsetTabular::automaticPopupCompletion() const
6347 {
6348         return lyxrc.completion_popup_text;
6349 }
6350
6351
6352 bool InsetTabular::showCompletionCursor() const
6353 {
6354         return lyxrc.completion_cursor_text;
6355 }
6356
6357
6358 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
6359 {
6360         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
6361 }
6362
6363
6364 docstring InsetTabular::completionPrefix(Cursor const & cur) const
6365 {
6366         if (!completionSupported(cur))
6367                 return docstring();
6368         return cur.text()->completionPrefix(cur);
6369 }
6370
6371
6372 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
6373 {
6374         if (!completionSupported(cur))
6375                 return false;
6376
6377         return cur.text()->insertCompletion(cur, s, finished);
6378 }
6379
6380
6381 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y,
6382                                     Dimension & dim) const
6383 {
6384         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
6385         tm.completionPosAndDim(cur, x, y, dim);
6386 }
6387
6388
6389 void InsetTabular::string2params(string const & in, InsetTabular & inset)
6390 {
6391         istringstream data(in);
6392         Lexer lex;
6393         lex.setStream(data);
6394
6395         if (in.empty())
6396                 return;
6397
6398         string token;
6399         lex >> token;
6400         if (!lex || token != "tabular") {
6401                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
6402                 return;
6403         }
6404
6405         // This is part of the inset proper that is usually swallowed
6406         // by Buffer::readInset
6407         lex >> token;
6408         if (!lex || token != "Tabular") {
6409                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
6410                 return;
6411         }
6412
6413         inset.read(lex);
6414 }
6415
6416
6417 string InsetTabular::params2string(InsetTabular const & inset)
6418 {
6419         ostringstream data;
6420         data << "tabular" << ' ';
6421         inset.write(data);
6422         data << "\\end_inset\n";
6423         return data.str();
6424 }
6425
6426
6427 void InsetTabular::setLayoutForHiddenCells(DocumentClass const & dc)
6428 {
6429         for (Tabular::col_type c = 0; c < tabular.ncols(); ++c) {
6430                 for (Tabular::row_type r = 0; r < tabular.nrows(); ++r) {
6431                         if (!tabular.isPartOfMultiColumn(r,c) &&
6432                             !tabular.isPartOfMultiRow(r,c))
6433                                 continue;
6434
6435                         ParagraphList & parlist = tabular.cellInset(r,c)->paragraphs();
6436                         ParagraphList::iterator it = parlist.begin();
6437                         ParagraphList::iterator const en = parlist.end();
6438                         for (; it != en; ++it)
6439                                         it->setLayout(dc.plainLayout());
6440                 }
6441         }
6442 }
6443
6444
6445 } // namespace lyx