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