]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
Color lines of added/deleted rows/columns
[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              Color const incol, bool drawline, bool heavy = false)
4490 {
4491         Color const col = drawline ? incol : 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         // Colour the frame if rows/columns are added or deleted
4520         Color colour = Color_tabularline;
4521         if (tabular.column_info[col].change != Change::UNCHANGED
4522             || tabular.row_info[row].change != Change::UNCHANGED)
4523                 colour = InsetTableCell(*tabular.cellInset(cell)).paragraphs().front().lookupChange(0).color();
4524
4525         // Top
4526         bool drawline = tabular.topLine(cell)
4527                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
4528         bool heavy = tabular.use_booktabs
4529                         && (row == 0 || (tabular.is_long_tabular && row == 1 && tabular.ltCaption(0)))
4530                         && tabular.rowTopLine(row);
4531         if (tabular.topLineTrim(cell).first
4532             || (row > 0 && tabular.bottomLineTrim(tabular.cellIndex(row - 1, col)).first))
4533                 lt = 10;
4534         if (tabular.topLineTrim(cell).second
4535             || (row > 0 && tabular.bottomLineTrim(tabular.cellIndex(row - 1, col)).second))
4536                 rt = 10;
4537         tabline(pi, x, y, x + w, y, lt, rt, colour, drawline, heavy);
4538
4539         // Bottom
4540         lt = rt = 0;
4541         drawline = tabular.bottomLine(cell);
4542         row_type const lastrow = tabular.nrows() - 1;
4543         // Consider multi-rows
4544         row_type r = row;
4545         while (r < lastrow && tabular.isMultiRow(tabular.cellIndex(r, col))
4546                 && tabular.isPartOfMultiRow(r + 1, col))
4547                 r++;
4548         heavy = tabular.use_booktabs
4549                 && ((row == lastrow && tabular.rowBottomLine(row))
4550                     || (r == lastrow && tabular.rowBottomLine(r)));
4551         if (tabular.bottomLineTrim(cell).first)
4552                 lt = 10;
4553         if (tabular.bottomLineTrim(cell).second)
4554                 rt = 10;
4555         tabline(pi, x, y + h, x + w, y + h, lt, rt, colour, drawline, heavy);
4556
4557         // Left
4558         drawline = tabular.leftLine(cell)
4559                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
4560         tabline(pi, x, y, x, y + h, 0, 0, colour, drawline);
4561
4562         // Right
4563         x -= tabular.interColumnSpace(cell);
4564         col_type next_cell_col = col + 1;
4565         while (next_cell_col < tabular.ncols()
4566                 && tabular.isMultiColumn(tabular.cellIndex(row, next_cell_col)))
4567                 next_cell_col++;
4568         drawline = tabular.rightLine(cell)
4569                    || (next_cell_col < tabular.ncols()
4570                        && tabular.leftLine(tabular.cellIndex(row, next_cell_col)));
4571         tabline(pi, x + w, y, x + w, y + h, 0, 0, colour, drawline);
4572 }
4573
4574
4575 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
4576 {
4577         //lyxerr << "InsetTabular::edit: " << this << endl;
4578         cur.finishUndo();
4579         cur.push(*this);
4580         if (front) {
4581                 if (isRightToLeft(cur))
4582                         cur.idx() = tabular.getLastCellInRow(0);
4583                 else
4584                         cur.idx() = 0;
4585                 cur.pit() = 0;
4586                 cur.pos() = 0;
4587         } else {
4588                 if (isRightToLeft(cur))
4589                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
4590                 else
4591                         cur.idx() = tabular.numberofcells - 1;
4592                 cur.pit() = 0;
4593                 cur.pos() = cur.lastpos(); // FIXME crude guess
4594         }
4595         cur.setCurrentFont();
4596         // FIXME: this accesses the position cache before it is initialized
4597         //cur.bv().fitCursor();
4598 }
4599
4600
4601 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
4602 {
4603         // In a longtable, tell captions what the current float is
4604         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
4605         string const saveflt = cnts.current_float();
4606         if (tabular.is_long_tabular) {
4607                 cnts.current_float("table");
4608                 // in longtables, we only step the counter once
4609                 cnts.step(from_ascii("table"), utype);
4610                 cnts.isLongtable(true);
4611         }
4612
4613         ParIterator it2 = it;
4614         it2.forwardPos();
4615         size_t const end = it2.nargs();
4616         for ( ; it2.idx() < end; it2.top().forwardIdx())
4617                 buffer().updateBuffer(it2, utype);
4618
4619         //reset afterwards
4620         if (tabular.is_long_tabular) {
4621                 cnts.current_float(saveflt);
4622                 cnts.isLongtable(false);
4623         }
4624 }
4625
4626
4627 void InsetTabular::addToToc(DocIterator const & cpit, bool output_active,
4628                                                         UpdateType utype, TocBackend & backend) const
4629 {
4630         DocIterator dit = cpit;
4631         dit.forwardPos();
4632         size_t const end = dit.nargs();
4633         for ( ; dit.idx() < end; dit.top().forwardIdx())
4634                 cell(dit.idx())->addToToc(dit, output_active, utype, backend);
4635 }
4636
4637
4638 bool InsetTabular::hitSelectRow(BufferView const & bv, int x) const
4639 {
4640         int const x0 = xo(bv) + ADD_TO_TABULAR_WIDTH;
4641         return x < x0 || x > x0 + tabular.width();
4642 }
4643
4644
4645 bool InsetTabular::hitSelectColumn(BufferView const & bv, int y) const
4646 {
4647         int const y0 = yo(bv) - tabular.rowAscent(0) + tabular.offsetVAlignment();
4648         // FIXME: using ADD_TO_TABULAR_WIDTH is not really correct since
4649         // there is no margin added vertically to tabular insets.
4650         // However, it works for now.
4651         return y < y0 + ADD_TO_TABULAR_WIDTH || y > y0 + tabular.height() - ADD_TO_TABULAR_WIDTH;
4652 }
4653
4654
4655 bool InsetTabular::clickable(BufferView const & bv, int x, int y) const
4656 {
4657         return hitSelectRow(bv, x) || hitSelectColumn(bv, y);
4658 }
4659
4660
4661 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
4662 {
4663         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
4664                              << "\n  cur:" << cur);
4665         CursorSlice sl = cur.top();
4666         Cursor & bvcur = cur.bv().cursor();
4667
4668         FuncCode const act = cmd.action();
4669
4670         switch (act) {
4671
4672         case LFUN_MOUSE_PRESS: {
4673                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
4674                 // select row
4675                 if (hitSelectRow(cur.bv(), cmd.x())) {
4676                         row_type r = rowFromY(cur, cmd.y());
4677                         cur.idx() = tabular.getFirstCellInRow(r);
4678                         cur.pit() = 0;
4679                         cur.pos() = 0;
4680                         cur.resetAnchor();
4681                         cur.idx() = tabular.getLastCellInRow(r);
4682                         cur.pit() = cur.lastpit();
4683                         cur.pos() = cur.lastpos();
4684                         cur.selection(true);
4685                         bvcur = cur;
4686                         rowselect_ = true;
4687                         break;
4688                 }
4689                 // select column
4690                 if (hitSelectColumn(cur.bv(), cmd.y())) {
4691                         col_type c = columnFromX(cur, cmd.x());
4692                         cur.idx() = tabular.cellIndex(0, c);
4693                         cur.pit() = 0;
4694                         cur.pos() = 0;
4695                         cur.resetAnchor();
4696                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
4697                         cur.pit() = cur.lastpit();
4698                         cur.pos() = cur.lastpos();
4699                         cur.selection(true);
4700                         bvcur = cur;
4701                         colselect_ = true;
4702                         break;
4703                 }
4704                 // do not reset cursor/selection if we have selected
4705                 // some cells (bug 2715).
4706                 if (cmd.button() == mouse_button::button3
4707                     && &bvcur.selBegin().inset() == this
4708                     && bvcur.selIsMultiCell())
4709                         ;
4710                 else
4711                         // Let InsetTableCell do it
4712                         cell(cur.idx())->dispatch(cur, cmd);
4713                 break;
4714         }
4715         case LFUN_MOUSE_MOTION:
4716                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
4717                 if (cmd.button() == mouse_button::button1) {
4718                         // only accept motions to places not deeper nested than the real anchor
4719                         if (!bvcur.realAnchor().hasPart(cur)) {
4720                                 cur.undispatched();
4721                                 break;
4722                         }
4723                         // select (additional) row
4724                         if (rowselect_) {
4725                                 row_type r = rowFromY(cur, cmd.y());
4726                                 cur.idx() = tabular.getLastCellInRow(r);
4727                                 // we need to reset the cursor's pit and pos now, as the old ones
4728                                 // may no longer be valid.
4729                                 cur.pit() = 0;
4730                                 cur.pos() = 0;
4731                                 bvcur.setCursor(cur);
4732                                 bvcur.selection(true);
4733                                 break;
4734                         }
4735                         // select (additional) column
4736                         if (colselect_) {
4737                                 col_type c = columnFromX(cur, cmd.x());
4738                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
4739                                 // we need to reset the cursor's pit and pos now, as the old ones
4740                                 // may no longer be valid.
4741                                 cur.pit() = 0;
4742                                 cur.pos() = 0;
4743                                 bvcur.setCursor(cur);
4744                                 bvcur.selection(true);
4745                                 break;
4746                         }
4747                         // only update if selection changes
4748                         if (bvcur.idx() == cur.idx() &&
4749                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
4750                                 cur.noScreenUpdate();
4751                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
4752                         bvcur.setCursor(cur);
4753                         bvcur.selection(true);
4754                         // if this is a multicell selection, we just set the cursor to
4755                         // the beginning of the cell's text.
4756                         if (bvcur.selIsMultiCell()) {
4757                                 bvcur.pit() = bvcur.lastpit();
4758                                 bvcur.pos() = bvcur.lastpos();
4759                         }
4760                 }
4761                 break;
4762
4763         case LFUN_MOUSE_RELEASE:
4764                 rowselect_ = false;
4765                 colselect_ = false;
4766                 break;
4767
4768         case LFUN_CELL_BACKWARD:
4769                 movePrevCell(cur);
4770                 cur.selection(false);
4771                 break;
4772
4773         case LFUN_CELL_FORWARD:
4774                 moveNextCell(cur);
4775                 cur.selection(false);
4776                 break;
4777
4778         case LFUN_CHAR_FORWARD_SELECT:
4779         case LFUN_CHAR_FORWARD:
4780         case LFUN_CHAR_BACKWARD_SELECT:
4781         case LFUN_CHAR_BACKWARD:
4782         case LFUN_CHAR_RIGHT_SELECT:
4783         case LFUN_CHAR_RIGHT:
4784         case LFUN_CHAR_LEFT_SELECT:
4785         case LFUN_CHAR_LEFT:
4786         case LFUN_WORD_FORWARD:
4787         case LFUN_WORD_FORWARD_SELECT:
4788         case LFUN_WORD_BACKWARD:
4789         case LFUN_WORD_BACKWARD_SELECT:
4790         case LFUN_WORD_RIGHT:
4791         case LFUN_WORD_RIGHT_SELECT:
4792         case LFUN_WORD_LEFT:
4793         case LFUN_WORD_LEFT_SELECT: {
4794                 // determine whether we move to next or previous cell, where to enter
4795                 // the new cell from, and which command to "finish" (i.e., exit the
4796                 // inset) with:
4797                 bool next_cell;
4798                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
4799                 FuncCode finish_lfun;
4800
4801                 if (act == LFUN_CHAR_FORWARD
4802                                 || act == LFUN_CHAR_FORWARD_SELECT
4803                                 || act == LFUN_WORD_FORWARD
4804                                 || act == LFUN_WORD_FORWARD_SELECT) {
4805                         next_cell = true;
4806                         finish_lfun = LFUN_FINISHED_FORWARD;
4807                 }
4808                 else if (act == LFUN_CHAR_BACKWARD
4809                                 || act == LFUN_CHAR_BACKWARD_SELECT
4810                                 || act == LFUN_WORD_BACKWARD
4811                                 || act == LFUN_WORD_BACKWARD_SELECT) {
4812                         next_cell = false;
4813                         finish_lfun = LFUN_FINISHED_BACKWARD;
4814                 }
4815                 // LEFT or RIGHT commands --- the interpretation will depend on the
4816                 // table's direction.
4817                 else {
4818                         bool const right = act == LFUN_CHAR_RIGHT
4819                                 || act == LFUN_CHAR_RIGHT_SELECT
4820                                 || act == LFUN_WORD_RIGHT
4821                                 || act == LFUN_WORD_RIGHT_SELECT;
4822                         next_cell = isRightToLeft(cur) != right;
4823
4824                         if (lyxrc.visual_cursor)
4825                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
4826
4827                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
4828                 }
4829
4830                 bool const select =     act == LFUN_CHAR_FORWARD_SELECT
4831                     || act == LFUN_CHAR_BACKWARD_SELECT
4832                     || act == LFUN_CHAR_RIGHT_SELECT
4833                     || act == LFUN_CHAR_LEFT_SELECT
4834                         || act == LFUN_WORD_FORWARD_SELECT
4835                         || act == LFUN_WORD_RIGHT_SELECT
4836                         || act == LFUN_WORD_BACKWARD_SELECT
4837                         || act == LFUN_WORD_LEFT_SELECT;
4838
4839                 // If we have a multicell selection or we're
4840                 // not doing some LFUN_*_SELECT thing anyway...
4841                 if (!cur.selIsMultiCell() || !select) {
4842                         col_type const c = tabular.cellColumn(cur.idx());
4843                         row_type const r = tabular.cellRow(cur.idx());
4844                         // Are we trying to select the whole cell and is the whole cell
4845                         // not yet selected?
4846                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
4847                                 ((next_cell && cur.pit() == cur.lastpit()
4848                                 && cur.pos() == cur.lastpos())
4849                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
4850
4851                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
4852
4853                         // ...try to dispatch to the cell's inset.
4854                         cell(cur.idx())->dispatch(cur, cmd);
4855
4856                         // When we already have a selection we want to select the whole cell
4857                         // before going to the next cell.
4858                         if (select_whole && !empty_cell){
4859                                 getText(cur.idx())->selectAll(cur);
4860                                 cur.dispatched();
4861                                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4862                                 break;
4863                         }
4864
4865                         // FIXME: When we support the selection of an empty cell, remove
4866                         // the !empty_cell from this condition. For now we jump to the next
4867                         // cell if the current cell is empty.
4868                         if (cur.result().dispatched() && !empty_cell)
4869                                 break;
4870                 }
4871
4872                 // move to next/prev cell, as appropriate
4873                 // note that we will always do this if we're selecting and we have
4874                 // a multicell selection
4875                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
4876                         << " cell from: " << int(entry_from));
4877                 if (next_cell)
4878                         moveNextCell(cur, entry_from);
4879                 else
4880                         movePrevCell(cur, entry_from);
4881                 // if we're exiting the table, call the appropriate FINISHED lfun
4882                 if (sl == cur.top()) {
4883                         cmd = FuncRequest(finish_lfun);
4884                         cur.undispatched();
4885                 } else
4886                         cur.dispatched();
4887
4888                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4889                 break;
4890
4891         }
4892
4893         case LFUN_DOWN_SELECT:
4894         case LFUN_DOWN:
4895                 if (!(cur.selection() && cur.selIsMultiCell()))
4896                         cell(cur.idx())->dispatch(cur, cmd);
4897
4898                 cur.dispatched(); // override the cell's decision
4899                 if (sl == cur.top()) {
4900                         // if our Text didn't do anything to the cursor
4901                         // then we try to put the cursor into the cell below
4902                         // setting also the right targetX.
4903                         cur.selHandle(act == LFUN_DOWN_SELECT);
4904                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
4905                                 int const xtarget = cur.targetX();
4906                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4907                                 // an inconsistent state until pos() has been set. Be careful
4908                                 // what you do with it!
4909                                 cur.idx() = tabular.cellBelow(cur.idx());
4910                                 cur.pit() = 0;
4911                                 TextMetrics const & tm =
4912                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
4913                                 cur.pos() = tm.x2pos(cur.pit(), 0, xtarget);
4914                                 cur.setCurrentFont();
4915                         }
4916                 }
4917                 if (sl == cur.top()) {
4918                         // we trick it to go to forward after leaving the
4919                         // tabular.
4920                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
4921                         cur.undispatched();
4922                 }
4923                 if (cur.selIsMultiCell()) {
4924                         cur.pit() = cur.lastpit();
4925                         cur.pos() = cur.lastpos();
4926                         cur.setCurrentFont();
4927                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4928                         return;
4929                 }
4930                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4931                 break;
4932
4933         case LFUN_UP_SELECT:
4934         case LFUN_UP:
4935                 if (!(cur.selection() && cur.selIsMultiCell()))
4936                         cell(cur.idx())->dispatch(cur, cmd);
4937                 cur.dispatched(); // override the cell's decision
4938                 if (sl == cur.top()) {
4939                         // if our Text didn't do anything to the cursor
4940                         // then we try to put the cursor into the cell above
4941                         // setting also the right targetX.
4942                         cur.selHandle(act == LFUN_UP_SELECT);
4943                         if (tabular.cellRow(cur.idx()) != 0) {
4944                                 int const xtarget = cur.targetX();
4945                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4946                                 // an inconsistent state until pos() has been set. Be careful
4947                                 // what you do with it!
4948                                 cur.idx() = tabular.cellAbove(cur.idx());
4949                                 cur.pit() = cur.lastpit();
4950                                 Text const * text = cell(cur.idx())->getText(0);
4951                                 TextMetrics const & tm = cur.bv().textMetrics(text);
4952                                 ParagraphMetrics const & pm =
4953                                         tm.parMetrics(cur.lastpit());
4954                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, xtarget);
4955                                 cur.setCurrentFont();
4956                         }
4957                 }
4958                 if (sl == cur.top()) {
4959                         cmd = FuncRequest(LFUN_UP);
4960                         cur.undispatched();
4961                 }
4962                 if (cur.selIsMultiCell()) {
4963                         cur.pit() = 0;
4964                         cur.pos() = cur.lastpos();
4965                         cur.setCurrentFont();
4966                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4967                         return;
4968                 }
4969                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4970                 break;
4971
4972         case LFUN_LAYOUT_TABULAR:
4973                 cur.bv().showDialog("tabular");
4974                 break;
4975
4976         case LFUN_INSET_MODIFY:
4977                 // we come from the dialog
4978                 if (cmd.getArg(0) == "tabular")
4979                         tabularFeatures(cur, cmd.getLongArg(1));
4980                 else
4981                         cur.undispatched();
4982                 break;
4983
4984         case LFUN_TABULAR_FEATURE:
4985                 tabularFeatures(cur, to_utf8(cmd.argument()));
4986                 break;
4987
4988         // insert file functions
4989         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
4990         case LFUN_FILE_INSERT_PLAINTEXT:
4991                 // FIXME UNICODE
4992                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
4993                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
4994                                 FileName(to_utf8(cmd.argument())));
4995                         if (tmpstr.empty())
4996                                 break;
4997                         cur.recordUndoInset();
4998                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
4999                                 // content has been replaced,
5000                                 // so cursor might be invalid
5001                                 cur.pos() = cur.lastpos();
5002                                 cur.pit() = cur.lastpit();
5003                                 bvcur.setCursor(cur);
5004                         } else
5005                                 cur.undispatched();
5006                 }
5007                 break;
5008
5009         case LFUN_CUT:
5010                 if (cur.selIsMultiCell()) {
5011                         if (copySelection(cur)) {
5012                                 cur.recordUndoInset();
5013                                 cutSelection(cur);
5014                         }
5015                 } else
5016                         cell(cur.idx())->dispatch(cur, cmd);
5017                 break;
5018
5019         case LFUN_SELF_INSERT:
5020                 if (cur.selIsMultiCell()) {
5021                         cur.recordUndoInset();
5022                         cutSelection(cur);
5023                         BufferView * bv = &cur.bv();
5024                         docstring::const_iterator cit = cmd.argument().begin();
5025                         docstring::const_iterator const end = cmd.argument().end();
5026                         for (; cit != end; ++cit)
5027                                 bv->translateAndInsert(*cit, getText(cur.idx()), cur);
5028
5029                         cur.resetAnchor();
5030                         bv->bookmarkEditPosition();
5031                 } else
5032                         cell(cur.idx())->dispatch(cur, cmd);
5033                 break;
5034
5035         case LFUN_CHAR_DELETE_BACKWARD:
5036         case LFUN_CHAR_DELETE_FORWARD:
5037                 if (cur.selIsMultiCell()) {
5038                         cur.recordUndoInset();
5039                         cutSelection(cur);
5040                 } else
5041                         cell(cur.idx())->dispatch(cur, cmd);
5042                 break;
5043
5044         case LFUN_COPY:
5045                 if (!cur.selection())
5046                         break;
5047                 if (cur.selIsMultiCell()) {
5048                         cur.finishUndo();
5049                         copySelection(cur);
5050                 } else
5051                         cell(cur.idx())->dispatch(cur, cmd);
5052                 break;
5053
5054         case LFUN_CLIPBOARD_PASTE:
5055         case LFUN_PRIMARY_SELECTION_PASTE: {
5056                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
5057                         theClipboard().getAsText(Clipboard::PlainTextType) :
5058                         theSelection().get();
5059                 if (clip.empty())
5060                         break;
5061                 // pass to InsertPlaintextString, but
5062                 // only if we have multi-cell content
5063                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
5064                         cur.recordUndoInset();
5065                         if (insertPlaintextString(cur.bv(), clip, false)) {
5066                                 // content has been replaced,
5067                                 // so cursor might be invalid
5068                                 cur.pos() = cur.lastpos();
5069                                 cur.pit() = cur.lastpit();
5070                                 bvcur.setCursor(cur);
5071                                 break;
5072                         }
5073                 }
5074                 // Let the cell handle normal text
5075                 cell(cur.idx())->dispatch(cur, cmd);
5076                 break;
5077         }
5078
5079         case LFUN_PASTE:
5080                 if (!tabularStackDirty()) {
5081                         // Check if we have plain text or HTML with rows/columns.
5082                         // and if so, pass over to LFUN_CLIPBOARD_PASTE
5083                         if (theClipboard().hasTextContents(Clipboard::AnyTextType)
5084                             && !theClipboard().hasTextContents(Clipboard::LyXTextType)) {
5085                                 docstring const clip =
5086                                         theClipboard().getAsText(Clipboard::AnyTextType);
5087                                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
5088                                         FuncRequest ncmd = FuncRequest(LFUN_CLIPBOARD_PASTE, cmd.argument());
5089                                         doDispatch(cur, ncmd);
5090                                         break;
5091                                 }
5092                         }
5093                         if (!cur.selIsMultiCell())
5094                                 cell(cur.idx())->dispatch(cur, cmd);
5095                         break;
5096                 }
5097                 if (theClipboard().isInternal()) {
5098                         cur.recordUndoInset();
5099                         pasteClipboard(cur);
5100                 }
5101                 break;
5102
5103         case LFUN_CHANGE_ACCEPT:
5104         case LFUN_CHANGE_REJECT:
5105         case LFUN_FONT_EMPH:
5106         case LFUN_FONT_BOLD:
5107         case LFUN_FONT_BOLDSYMBOL:
5108         case LFUN_FONT_ROMAN:
5109         case LFUN_FONT_NOUN:
5110         case LFUN_FONT_ITAL:
5111         case LFUN_FONT_FRAK:
5112         case LFUN_FONT_TYPEWRITER:
5113         case LFUN_FONT_SANS:
5114         case LFUN_TEXTSTYLE_APPLY:
5115         case LFUN_TEXTSTYLE_UPDATE:
5116         case LFUN_FONT_SIZE:
5117         case LFUN_FONT_UNDERLINE:
5118         case LFUN_FONT_STRIKEOUT:
5119         case LFUN_FONT_CROSSOUT:
5120         case LFUN_FONT_UNDERUNDERLINE:
5121         case LFUN_FONT_UNDERWAVE:
5122         case LFUN_LANGUAGE:
5123         case LFUN_PARAGRAPH_PARAMS_APPLY:
5124         case LFUN_PARAGRAPH_PARAMS:
5125         case LFUN_WORD_CAPITALIZE:
5126         case LFUN_WORD_UPCASE:
5127         case LFUN_WORD_LOWCASE:
5128         case LFUN_CHARS_TRANSPOSE: {
5129                 bool const ct = (act == LFUN_CHANGE_ACCEPT || act == LFUN_CHANGE_REJECT);
5130                 if (cur.selIsMultiCell()) {
5131                         row_type rs, re;
5132                         col_type cs, ce;
5133                         getSelection(cur, rs, re, cs, ce);
5134                         Cursor tmpcur = cur;
5135                         for (row_type r = rs; r <= re; ++r) {
5136                                 if (ct && cs == 0 && ce == tabular.ncols() - 1) {
5137                                         // whole row selected
5138                                         if (act == LFUN_CHANGE_ACCEPT) {
5139                                                 if (tabular.row_info[r].change == Change::INSERTED)
5140                                                         tabular.row_info[r].change = Change::UNCHANGED;
5141                                                 else if (tabular.row_info[r].change == Change::DELETED) {
5142                                                         tabular.deleteRow(r, true);
5143                                                         --re;
5144                                                         continue;
5145                                                 }
5146                                         } else {
5147                                                 if (tabular.row_info[r].change == Change::DELETED)
5148                                                         tabular.row_info[r].change = Change::UNCHANGED;
5149                                                 else if (tabular.row_info[r].change == Change::INSERTED) {
5150                                                         tabular.deleteRow(r, true);
5151                                                         --re;
5152                                                         continue;
5153                                                 }
5154                                         }
5155                                 }
5156                                 for (col_type c = cs; c <= ce; ++c) {
5157                                         if (ct && rs == 0 && re == tabular.nrows() - 1) {
5158                                                 // whole col selected
5159                                                 if (act == LFUN_CHANGE_ACCEPT) {
5160                                                         if (tabular.column_info[c].change == Change::INSERTED)
5161                                                                 tabular.column_info[c].change = Change::UNCHANGED;
5162                                                         else if (tabular.column_info[c].change == Change::DELETED) {
5163                                                                 tabular.deleteColumn(c, true);
5164                                                                 --ce;
5165                                                                 continue;
5166                                                         }
5167                                                 } else {
5168                                                         if (tabular.column_info[c].change == Change::DELETED)
5169                                                                 tabular.column_info[c].change = Change::UNCHANGED;
5170                                                         else if (tabular.column_info[c].change == Change::INSERTED) {
5171                                                                 tabular.deleteColumn(c, true);
5172                                                                 --ce;
5173                                                                 continue;
5174                                                         }
5175                                                 }
5176                                         }
5177                                         // cursor follows cell:
5178                                         tmpcur.idx() = tabular.cellIndex(r, c);
5179                                         // select this cell only:
5180                                         tmpcur.pit() = 0;
5181                                         tmpcur.pos() = 0;
5182                                         tmpcur.resetAnchor();
5183                                         tmpcur.pit() = tmpcur.lastpit();
5184                                         tmpcur.pos() = tmpcur.top().lastpos();
5185                                         tmpcur.setCursor(tmpcur);
5186                                         tmpcur.setSelection();
5187                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
5188                                 }
5189                         }
5190                         if (ct) {
5191                                 // cursor might be invalid
5192                                 cur.fixIfBroken();
5193                         }
5194                         break;
5195                 } else {
5196                         cell(cur.idx())->dispatch(cur, cmd);
5197                         break;
5198                 }
5199         }
5200
5201         case LFUN_CHANGE_NEXT:
5202         case LFUN_CHANGE_PREVIOUS: {
5203                 // BufferView::dispatch has already moved the cursor, we just
5204                 // need to select here if we have a changed row or column
5205                 if (tabular.row_info[tabular.cellRow(cur.idx())].change != Change::UNCHANGED) {
5206                         // select row
5207                         cur.idx() = tabular.getFirstCellInRow(tabular.cellRow(cur.idx()));
5208                         cur.pit() = 0;
5209                         cur.pos() = 0;
5210                         cur.resetAnchor();
5211                         cur.idx() = tabular.getLastCellInRow(tabular.cellRow(cur.idx()));
5212                         cur.pit() = cur.lastpit();
5213                         cur.pos() = cur.lastpos();
5214                         cur.selection(true);
5215                         bvcur = cur;
5216                         rowselect_ = true;
5217                 }
5218                 else if (tabular.column_info[tabular.cellColumn(cur.idx())].change != Change::UNCHANGED) {
5219                         // select column
5220                         cur.idx() = tabular.cellIndex(0, tabular.cellColumn(cur.idx()));
5221                         cur.pit() = 0;
5222                         cur.pos() = 0;
5223                         cur.resetAnchor();
5224                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, tabular.cellColumn(cur.idx()));
5225                         cur.pit() = cur.lastpit();
5226                         cur.pos() = cur.lastpos();
5227                         cur.selection(true);
5228                         bvcur = cur;
5229                         colselect_ = true;
5230                 }
5231                 break;
5232         }
5233
5234         case LFUN_INSET_SETTINGS:
5235                 // relay this lfun to Inset, not to the cell.
5236                 Inset::doDispatch(cur, cmd);
5237                 break;
5238
5239         default:
5240                 // we try to handle this event in the insets dispatch function.
5241                 cell(cur.idx())->dispatch(cur, cmd);
5242                 break;
5243         }
5244 }
5245
5246
5247 bool InsetTabular::getFeatureStatus(Cursor & cur, string const & s,
5248                       string const & argument, FuncStatus & status) const
5249 {
5250
5251                 int action = Tabular::LAST_ACTION;
5252                 int i = 0;
5253                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
5254                         if (tabularFeature[i].feature == s) {
5255                                 action = tabularFeature[i].action;
5256                                 break;
5257                         }
5258                 }
5259                 if (action == Tabular::LAST_ACTION) {
5260                         status.clear();
5261                         status.setUnknown(true);
5262                         return true;
5263                 }
5264
5265                 row_type sel_row_start = 0;
5266                 row_type sel_row_end = 0;
5267                 col_type sel_col_start = 0;
5268                 col_type sel_col_end = 0;
5269                 Tabular::ltType dummyltt;
5270                 bool flag = true;
5271
5272                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5273
5274                 switch (action) {
5275                 case Tabular::SET_PWIDTH:
5276                 case Tabular::SET_MPWIDTH:
5277                 case Tabular::TOGGLE_VARWIDTH_COLUMN:
5278                 case Tabular::SET_SPECIAL_COLUMN:
5279                 case Tabular::SET_SPECIAL_MULTICOLUMN:
5280                 case Tabular::APPEND_ROW:
5281                 case Tabular::APPEND_COLUMN:
5282                 case Tabular::DELETE_ROW:
5283                 case Tabular::DELETE_COLUMN:
5284                 case Tabular::COPY_ROW:
5285                 case Tabular::COPY_COLUMN:
5286                 case Tabular::SET_TOP_SPACE:
5287                 case Tabular::SET_BOTTOM_SPACE:
5288                 case Tabular::SET_INTERLINE_SPACE:
5289                         status.clear();
5290                         return true;
5291
5292                 case Tabular::SET_TABULAR_WIDTH:
5293                         status.setEnabled(!tabular.rotate
5294                                 && tabular.tabular_valignment == Tabular::LYX_VALIGN_MIDDLE);
5295                         break;
5296
5297                 case Tabular::MOVE_COLUMN_RIGHT:
5298                 case Tabular::MOVE_COLUMN_LEFT:
5299                 case Tabular::MOVE_ROW_DOWN:
5300                 case Tabular::MOVE_ROW_UP: {
5301                         if (cur.selection()) {
5302                                 status.message(_("Selections not supported."));
5303                                 status.setEnabled(false);
5304                                 break;
5305                         }
5306
5307                         if ((action == Tabular::MOVE_COLUMN_RIGHT &&
5308                                 tabular.ncols() == tabular.cellColumn(cur.idx()) + 1) ||
5309                             (action == Tabular::MOVE_COLUMN_LEFT &&
5310                                 tabular.cellColumn(cur.idx()) == 0) ||
5311                             (action == Tabular::MOVE_ROW_DOWN &&
5312                                 tabular.nrows() == tabular.cellRow(cur.idx()) + 1) ||
5313                             (action == Tabular::MOVE_ROW_UP &&
5314                                 tabular.cellRow(cur.idx()) == 0)) {
5315                                         status.setEnabled(false);
5316                                         break;
5317                         }
5318
5319                         if (action == Tabular::MOVE_COLUMN_RIGHT ||
5320                             action == Tabular::MOVE_COLUMN_LEFT) {
5321                                 if (tabular.hasMultiColumn(tabular.cellColumn(cur.idx())) ||
5322                                     tabular.hasMultiColumn(tabular.cellColumn(cur.idx()) +
5323                                         (action == Tabular::MOVE_COLUMN_RIGHT ? 1 : -1))) {
5324                                         status.message(_("Multi-column in current or"
5325                                                          " destination column."));
5326                                         status.setEnabled(false);
5327                                         break;
5328                                 }
5329                         }
5330
5331                         if (action == Tabular::MOVE_ROW_DOWN ||
5332                             action == Tabular::MOVE_ROW_UP) {
5333                                 if (tabular.hasMultiRow(tabular.cellRow(cur.idx())) ||
5334                                     tabular.hasMultiRow(tabular.cellRow(cur.idx()) +
5335                                         (action == Tabular::MOVE_ROW_DOWN ? 1 : -1))) {
5336                                         status.message(_("Multi-row in current or"
5337                                                          " destination row."));
5338                                         status.setEnabled(false);
5339                                         break;
5340                                 }
5341                         }
5342
5343                         status.setEnabled(true);
5344                         break;
5345                 }
5346
5347                 case Tabular::SET_DECIMAL_POINT:
5348                         status.setEnabled(
5349                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
5350                         break;
5351
5352                 case Tabular::SET_MULTICOLUMN:
5353                 case Tabular::UNSET_MULTICOLUMN:
5354                 case Tabular::MULTICOLUMN:
5355                         // If a row is set as longtable caption, it must not be allowed
5356                         // to unset that this row is a multicolumn.
5357                         status.setEnabled(sel_row_start == sel_row_end
5358                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5359                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
5360                         break;
5361
5362                 case Tabular::SET_MULTIROW:
5363                 case Tabular::UNSET_MULTIROW:
5364                 case Tabular::MULTIROW:
5365                         // If a row is set as longtable caption, it must not be allowed
5366                         // to unset that this row is a multirow.
5367                         status.setEnabled(sel_col_start == sel_col_end
5368                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5369                         status.setOnOff(tabular.isMultiRow(cur.idx()));
5370                         break;
5371
5372                 case Tabular::SET_ALL_LINES:
5373                 case Tabular::UNSET_ALL_LINES:
5374                 case Tabular::SET_INNER_LINES:
5375                 case Tabular::SET_BORDER_LINES:
5376                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
5377                         break;
5378
5379                 case Tabular::RESET_FORMAL_DEFAULT:
5380                         status.setEnabled(tabular.use_booktabs);
5381                         break;
5382
5383                 case Tabular::SET_LINE_TOP:
5384                 case Tabular::SET_LINE_BOTTOM:
5385                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
5386                         break;
5387
5388                 case Tabular::SET_LINE_LEFT:
5389                 case Tabular::SET_LINE_RIGHT:
5390                         status.setEnabled(!tabular.use_booktabs
5391                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5392                         break;
5393
5394                 case Tabular::SET_LTRIM_TOP:
5395                 case Tabular::SET_RTRIM_TOP:
5396                         status.setEnabled(tabular.use_booktabs
5397                                           && tabular.cellRow(cur.idx()) != 0
5398                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5399                         break;
5400
5401                 case Tabular::SET_LTRIM_BOTTOM:
5402                 case Tabular::SET_RTRIM_BOTTOM:
5403                         status.setEnabled(tabular.use_booktabs
5404                                           && tabular.cellRow(cur.idx()) != tabular.nrows() - 1
5405                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5406                         break;
5407
5408                 case Tabular::TOGGLE_LINE_TOP:
5409                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
5410                         status.setOnOff(tabular.topLine(cur.idx()));
5411                         break;
5412
5413                 case Tabular::TOGGLE_LINE_BOTTOM:
5414                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
5415                         status.setOnOff(tabular.bottomLine(cur.idx()));
5416                         break;
5417
5418                 case Tabular::TOGGLE_LINE_LEFT:
5419                         status.setEnabled(!tabular.use_booktabs
5420                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5421                         status.setOnOff(tabular.leftLine(cur.idx()));
5422                         break;
5423
5424                 case Tabular::TOGGLE_LINE_RIGHT:
5425                         status.setEnabled(!tabular.use_booktabs
5426                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5427                         status.setOnOff(tabular.rightLine(cur.idx()));
5428                         break;
5429
5430                 case Tabular::TOGGLE_LTRIM_TOP:
5431                         status.setEnabled(tabular.use_booktabs
5432                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5433                         status.setOnOff(tabular.topLineTrim(cur.idx()).first);
5434                         break;
5435
5436                 case Tabular::TOGGLE_RTRIM_TOP:
5437                         status.setEnabled(tabular.use_booktabs
5438                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5439                         status.setOnOff(tabular.topLineTrim(cur.idx()).second);
5440                         break;
5441
5442                 case Tabular::TOGGLE_LTRIM_BOTTOM:
5443                         status.setEnabled(tabular.use_booktabs
5444                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5445                         status.setOnOff(tabular.bottomLineTrim(cur.idx()).first);
5446                         break;
5447
5448                 case Tabular::TOGGLE_RTRIM_BOTTOM:
5449                         status.setEnabled(tabular.use_booktabs
5450                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5451                         status.setOnOff(tabular.bottomLineTrim(cur.idx()).second);
5452                         break;
5453
5454                 // multirow cells only inherit the alignment of the column if the column has
5455                 // no width, otherwise they are left-aligned
5456                 // therefore allow always left but right and center only if there is no width
5457                 case Tabular::M_ALIGN_LEFT:
5458                         flag = false;
5459                         // fall through
5460                 case Tabular::ALIGN_LEFT:
5461                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
5462                         break;
5463
5464                 case Tabular::M_ALIGN_RIGHT:
5465                         flag = false;
5466                         // fall through
5467                 case Tabular::ALIGN_RIGHT:
5468                         status.setEnabled(!(tabular.isMultiRow(cur.idx())
5469                                 && !tabular.getPWidth(cur.idx()).zero()));
5470                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
5471                         break;
5472
5473                 case Tabular::M_ALIGN_CENTER:
5474                         flag = false;
5475                         // fall through
5476                 case Tabular::ALIGN_CENTER:
5477                         status.setEnabled(!(tabular.isMultiRow(cur.idx())
5478                                 && !tabular.getPWidth(cur.idx()).zero()));
5479                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
5480                         break;
5481
5482                 case Tabular::ALIGN_BLOCK:
5483                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
5484                                 && !tabular.isMultiRow(cur.idx()));
5485                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
5486                         break;
5487
5488                 case Tabular::ALIGN_DECIMAL:
5489                         status.setEnabled(!tabular.isMultiRow(cur.idx())
5490                                 && !tabular.isMultiColumn(cur.idx()));
5491                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
5492                         break;
5493
5494                 case Tabular::M_VALIGN_TOP:
5495                         flag = false;
5496                         // fall through
5497                 case Tabular::VALIGN_TOP:
5498                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
5499                                 && !tabular.isMultiRow(cur.idx()));
5500                         status.setOnOff(
5501                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
5502                         break;
5503
5504                 case Tabular::M_VALIGN_BOTTOM:
5505                         flag = false;
5506                         // fall through
5507                 case Tabular::VALIGN_BOTTOM:
5508                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
5509                                 && !tabular.isMultiRow(cur.idx()));
5510                         status.setOnOff(
5511                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
5512                         break;
5513
5514                 case Tabular::M_VALIGN_MIDDLE:
5515                         flag = false;
5516                         // fall through
5517                 case Tabular::VALIGN_MIDDLE:
5518                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
5519                                 && !tabular.isMultiRow(cur.idx()));
5520                         status.setOnOff(
5521                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
5522                         break;
5523
5524                 case Tabular::SET_LONGTABULAR:
5525                 case Tabular::TOGGLE_LONGTABULAR:
5526                         // setting as longtable is not allowed when table is inside a float
5527                         if (cur.innerInsetOfType(FLOAT_CODE) != 0
5528                                 || cur.innerInsetOfType(WRAP_CODE) != 0)
5529                                 status.setEnabled(false);
5530                         else
5531                                 status.setEnabled(true);
5532                         status.setOnOff(tabular.is_long_tabular);
5533                         break;
5534
5535                 case Tabular::UNSET_LONGTABULAR:
5536                         status.setOnOff(!tabular.is_long_tabular);
5537                         break;
5538
5539                 case Tabular::TOGGLE_ROTATE_TABULAR:
5540                 case Tabular::SET_ROTATE_TABULAR:
5541                         status.setOnOff(tabular.rotate != 0);
5542                         break;
5543
5544                 case Tabular::TABULAR_VALIGN_TOP:
5545                         status.setEnabled(tabular.tabular_width.zero());
5546                         status.setOnOff(tabular.tabular_valignment
5547                                 == Tabular::LYX_VALIGN_TOP);
5548                         break;
5549                 case Tabular::TABULAR_VALIGN_MIDDLE:
5550                         status.setEnabled(tabular.tabular_width.zero());
5551                         status.setOnOff(tabular.tabular_valignment
5552                                 == Tabular::LYX_VALIGN_MIDDLE);
5553                         break;
5554                 case Tabular::TABULAR_VALIGN_BOTTOM:
5555                         status.setEnabled(tabular.tabular_width.zero());
5556                         status.setOnOff(tabular.tabular_valignment
5557                                 == Tabular::LYX_VALIGN_BOTTOM);
5558                         break;
5559
5560                 case Tabular::LONGTABULAR_ALIGN_LEFT:
5561                         status.setOnOff(tabular.longtabular_alignment
5562                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
5563                         break;
5564                 case Tabular::LONGTABULAR_ALIGN_CENTER:
5565                         status.setOnOff(tabular.longtabular_alignment
5566                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
5567                         break;
5568                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
5569                         status.setOnOff(tabular.longtabular_alignment
5570                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
5571                         break;
5572
5573                 case Tabular::UNSET_ROTATE_TABULAR:
5574                         status.setOnOff(tabular.rotate == 0);
5575                         break;
5576
5577                 case Tabular::TOGGLE_ROTATE_CELL:
5578                 case Tabular::SET_ROTATE_CELL:
5579                         status.setOnOff(!oneCellHasRotationState(false,
5580                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
5581                         break;
5582
5583                 case Tabular::UNSET_ROTATE_CELL:
5584                         status.setOnOff(!oneCellHasRotationState(true,
5585                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
5586                         break;
5587
5588                 case Tabular::SET_USEBOX:
5589                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
5590                         break;
5591
5592                 // every row can only be one thing:
5593                 // either a footer or header
5594                 case Tabular::SET_LTFIRSTHEAD:
5595                         status.setEnabled(sel_row_start == sel_row_end);
5596                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
5597                         break;
5598
5599                 case Tabular::UNSET_LTFIRSTHEAD:
5600                         status.setEnabled(sel_row_start == sel_row_end);
5601                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
5602                         break;
5603
5604                 case Tabular::SET_LTHEAD:
5605                         status.setEnabled(sel_row_start == sel_row_end);
5606                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
5607                         break;
5608
5609                 case Tabular::UNSET_LTHEAD:
5610                         status.setEnabled(sel_row_start == sel_row_end);
5611                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
5612                         break;
5613
5614                 case Tabular::SET_LTFOOT:
5615                         status.setEnabled(sel_row_start == sel_row_end);
5616                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
5617                         break;
5618
5619                 case Tabular::UNSET_LTFOOT:
5620                         status.setEnabled(sel_row_start == sel_row_end);
5621                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
5622                         break;
5623
5624                 case Tabular::SET_LTLASTFOOT:
5625                         status.setEnabled(sel_row_start == sel_row_end);
5626                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
5627                         break;
5628
5629                 case Tabular::UNSET_LTLASTFOOT:
5630                         status.setEnabled(sel_row_start == sel_row_end);
5631                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
5632                         break;
5633
5634                 case Tabular::SET_LTNEWPAGE:
5635                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
5636                         break;
5637                 case Tabular::UNSET_LTNEWPAGE:
5638                         status.setOnOff(!tabular.getLTNewPage(sel_row_start));
5639                         break;
5640
5641                 // only one row in head/firsthead/foot/lasthead can be the caption
5642                 // and a multirow cannot be set as caption
5643                 case Tabular::SET_LTCAPTION:
5644                         status.setEnabled(sel_row_start == sel_row_end
5645                                 && (!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
5646                                  || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
5647                                 && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
5648                                  || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
5649                                 && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
5650                                  || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
5651                                 && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
5652                                  || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT))
5653                                 && !tabular.isMultiRow(sel_row_start));
5654                         status.setOnOff(tabular.ltCaption(sel_row_start));
5655                         break;
5656
5657                 case Tabular::UNSET_LTCAPTION:
5658                         status.setEnabled(sel_row_start == sel_row_end && tabular.ltCaption(sel_row_start));
5659                         break;
5660
5661                 case Tabular::TOGGLE_LTCAPTION:
5662                         status.setEnabled(sel_row_start == sel_row_end && (tabular.ltCaption(sel_row_start)
5663                                 || ((!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
5664                                   || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
5665                                  && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
5666                                   || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
5667                                  && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
5668                                   || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
5669                                  && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
5670                                   || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT)))));
5671                         status.setOnOff(tabular.ltCaption(sel_row_start));
5672                         break;
5673
5674                 case Tabular::TOGGLE_BOOKTABS:
5675                 case Tabular::SET_BOOKTABS:
5676                         status.setOnOff(tabular.use_booktabs);
5677                         break;
5678
5679                 case Tabular::UNSET_BOOKTABS:
5680                         status.setOnOff(!tabular.use_booktabs);
5681                         break;
5682
5683                 default:
5684                         status.clear();
5685                         status.setEnabled(false);
5686                         break;
5687                 }
5688                 return true;
5689 }
5690
5691
5692 // function sets an object as defined in FuncStatus.h:
5693 // states OK, Unknown, Disabled, On, Off.
5694 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
5695                              FuncStatus & status) const
5696 {
5697         switch (cmd.action()) {
5698         case LFUN_INSET_MODIFY:
5699                 if (cmd.getArg(0) != "tabular")
5700                         break;
5701                 if (cmd.getArg(1) == "for-dialog") {
5702                         // The dialog is asking the status of a command
5703                         if (&cur.inset() != this)
5704                                 break;
5705                         string action = cmd.getArg(2);
5706                         string arg = cmd.getLongArg(3);
5707                         return getFeatureStatus(cur, action, arg, status);
5708                 } else {
5709                         // We always enable the lfun if it is coming from the dialog
5710                         // because the dialog makes sure all the settings are valid,
5711                         // even though the first argument might not be valid now.
5712                         status.setEnabled(true);
5713                         return true;
5714                 }
5715
5716         case LFUN_TABULAR_FEATURE: {
5717                 if (&cur.inset() != this)
5718                         break;
5719                 string action = cmd.getArg(0);
5720                 string arg = cmd.getLongArg(1);
5721                 return getFeatureStatus(cur, action, arg, status);
5722         }
5723
5724         case LFUN_CAPTION_INSERT: {
5725                 // caption is only allowed in caption cell of longtable
5726                 if (!tabular.ltCaption(tabular.cellRow(cur.idx()))) {
5727                         status.setEnabled(false);
5728                         return true;
5729                 }
5730                 // only standard caption is allowed
5731                 string arg = cmd.getArg(0);
5732                 if (!arg.empty() && arg != "Standard") {
5733                         status.setEnabled(false);
5734                         return true;
5735                 }
5736                 // check if there is already a caption
5737                 bool have_caption = false;
5738                 InsetTableCell itc = InsetTableCell(*tabular.cellInset(cur.idx()));
5739                 ParagraphList::const_iterator pit = itc.paragraphs().begin();
5740                 ParagraphList::const_iterator pend = itc.paragraphs().end();
5741                 for (; pit != pend; ++pit) {
5742                         InsetList::const_iterator it  = pit->insetList().begin();
5743                         InsetList::const_iterator end = pit->insetList().end();
5744                         for (; it != end; ++it) {
5745                                 if (it->inset->lyxCode() == CAPTION_CODE) {
5746                                         have_caption = true;
5747                                         break;
5748                                 }
5749                         }
5750                 }
5751                 status.setEnabled(!have_caption);
5752                 return true;
5753         }
5754
5755         // These are only enabled inside tabular
5756         case LFUN_CELL_BACKWARD:
5757         case LFUN_CELL_FORWARD:
5758                 status.setEnabled(true);
5759                 return true;
5760
5761         // disable these with multiple cells selected
5762         case LFUN_INSET_INSERT:
5763         case LFUN_TABULAR_INSERT:
5764         case LFUN_TABULAR_STYLE_INSERT:
5765         case LFUN_FLEX_INSERT:
5766         case LFUN_FLOAT_INSERT:
5767         case LFUN_FLOAT_WIDE_INSERT:
5768         case LFUN_FOOTNOTE_INSERT:
5769         case LFUN_MARGINALNOTE_INSERT:
5770         case LFUN_MATH_INSERT:
5771         case LFUN_MATH_MODE:
5772         case LFUN_MATH_MUTATE:
5773         case LFUN_MATH_DISPLAY:
5774         case LFUN_NOTE_INSERT:
5775         case LFUN_ARGUMENT_INSERT:
5776         case LFUN_BOX_INSERT:
5777         case LFUN_BRANCH_INSERT:
5778         case LFUN_PHANTOM_INSERT:
5779         case LFUN_WRAP_INSERT:
5780         case LFUN_PREVIEW_INSERT:
5781         case LFUN_ERT_INSERT: {
5782                 if (cur.selIsMultiCell()) {
5783                         status.setEnabled(false);
5784                         return true;
5785                 } else
5786                         return cell(cur.idx())->getStatus(cur, cmd, status);
5787         }
5788
5789         case LFUN_CHANGE_ACCEPT:
5790         case LFUN_CHANGE_REJECT: {
5791                 if (cur.selIsMultiCell()) {
5792                         row_type rs, re;
5793                         col_type cs, ce;
5794                         getSelection(cur, rs, re, cs, ce);
5795                         for (row_type r = rs; r <= re; ++r) {
5796                                 if (tabular.row_info[r].change != Change::UNCHANGED) {
5797                                         status.setEnabled(true);
5798                                         return true;
5799                                 }
5800                                 for (col_type c = cs; c <= ce; ++c) {
5801                                         if (tabular.column_info[c].change != Change::UNCHANGED) {
5802                                                 status.setEnabled(true);
5803                                                 return true;
5804                                         }
5805                                 }
5806                         }
5807                 } else {
5808                         if (tabular.row_info[tabular.cellRow(cur.idx())].change != Change::UNCHANGED) {
5809                                 status.setEnabled(true);
5810                                 return true;
5811                         }
5812                         else if (tabular.column_info[tabular.cellColumn(cur.idx())].change != Change::UNCHANGED) {
5813                                 status.setEnabled(true);
5814                                 return true;
5815                         }
5816                 }
5817                 return cell(cur.idx())->getStatus(cur, cmd, status);
5818         }
5819
5820         // disable in non-fixed-width cells
5821         case LFUN_PARAGRAPH_BREAK:
5822                 // multirow does not allow paragraph breaks
5823                 if (tabular.isMultiRow(cur.idx())) {
5824                         status.setEnabled(false);
5825                         return true;
5826                 }
5827                 // fall through
5828         case LFUN_NEWLINE_INSERT:
5829                 if ((tabular.isMultiColumn(cur.idx()) || tabular.isMultiRow(cur.idx()))
5830                     && tabular.getPWidth(cur.idx()).zero()) {
5831                         status.setEnabled(false);
5832                         return true;
5833                 }
5834                 return cell(cur.idx())->getStatus(cur, cmd, status);
5835
5836         case LFUN_NEWPAGE_INSERT:
5837                 status.setEnabled(false);
5838                 return true;
5839
5840         case LFUN_PASTE:
5841                 if (tabularStackDirty() && theClipboard().isInternal()) {
5842                         if (cur.selIsMultiCell()) {
5843                                 row_type rs, re;
5844                                 col_type cs, ce;
5845                                 getSelection(cur, rs, re, cs, ce);
5846                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
5847                                           && paste_tabular->nrows() == re - rs + 1)
5848                                         status.setEnabled(true);
5849                                 else {
5850                                         status.setEnabled(false);
5851                                         status.message(_("Selection size should match clipboard content."));
5852                                 }
5853                         } else
5854                                 status.setEnabled(true);
5855                         return true;
5856                 }
5857                 return cell(cur.idx())->getStatus(cur, cmd, status);
5858
5859         case LFUN_INSET_SETTINGS:
5860                 // relay this lfun to Inset, not to the cell.
5861                 return Inset::getStatus(cur, cmd, status);
5862
5863         default:
5864                 // we try to handle this event in the insets dispatch function.
5865                 return cell(cur.idx())->getStatus(cur, cmd, status);
5866         }
5867         return false;
5868 }
5869
5870
5871 Inset::DisplayType InsetTabular::display() const
5872 {
5873                 if (tabular.is_long_tabular) {
5874                         switch (tabular.longtabular_alignment) {
5875                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
5876                                 return AlignLeft;
5877                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
5878                                 return AlignCenter;
5879                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
5880                                 return AlignRight;
5881                         default:
5882                                 return AlignCenter;
5883                         }
5884                 } else
5885                         return Inline;
5886 }
5887
5888
5889 void InsetTabular::latex(otexstream & os, OutputParams const & runparams) const
5890 {
5891         tabular.latex(os, runparams);
5892 }
5893
5894
5895 int InsetTabular::plaintext(odocstringstream & os,
5896         OutputParams const & runparams, size_t max_length) const
5897 {
5898         os << '\n'; // output table on a new line
5899         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
5900         tabular.plaintext(os, runparams, dp, false, 0, max_length);
5901         return PLAINTEXT_NEWLINE;
5902 }
5903
5904
5905 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
5906 {
5907         int ret = 0;
5908         Inset * master = 0;
5909
5910         // FIXME: Why not pass a proper DocIterator here?
5911 #if 0
5912         // if the table is inside a float it doesn't need the informaltable
5913         // wrapper. Search for it.
5914         for (master = owner(); master; master = master->owner())
5915                 if (master->lyxCode() == FLOAT_CODE)
5916                         break;
5917 #endif
5918
5919         if (!master) {
5920                 os << "<informaltable>";
5921                 ++ret;
5922         }
5923         ret += tabular.docbook(os, runparams);
5924         if (!master) {
5925                 os << "</informaltable>";
5926                 ++ret;
5927         }
5928         return ret;
5929 }
5930
5931
5932 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
5933 {
5934         return tabular.xhtml(xs, rp);
5935 }
5936
5937
5938 void InsetTabular::validate(LaTeXFeatures & features) const
5939 {
5940         tabular.validate(features);
5941         features.useInsetLayout(getLayout());
5942 }
5943
5944
5945 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
5946 {
5947         return tabular.cellInset(idx);
5948 }
5949
5950
5951 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
5952 {
5953         return tabular.cellInset(idx);
5954 }
5955
5956
5957 void InsetTabular::cursorPos(BufferView const & bv,
5958                 CursorSlice const & sl, bool boundary, int & x, int & y) const
5959 {
5960         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
5961
5962         // y offset     correction
5963         y += cellYPos(sl.idx());
5964         y += tabular.textVOffset(sl.idx());
5965         y += tabular.offsetVAlignment();
5966
5967         // x offset correction
5968         x += cellXPos(sl.idx());
5969         x += tabular.textHOffset(sl.idx());
5970         x += ADD_TO_TABULAR_WIDTH;
5971 }
5972
5973
5974 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
5975 {
5976         int xx = 0;
5977         int yy = 0;
5978         Inset const & inset = *tabular.cellInset(cell);
5979         Point o = bv.coordCache().getInsets().xy(&inset);
5980         int const xbeg = o.x_ - tabular.textHOffset(cell);
5981         int const xend = xbeg + tabular.cellWidth(cell);
5982         row_type const row = tabular.cellRow(cell);
5983         int const ybeg = o.y_ - tabular.rowAscent(row)
5984                 - tabular.interRowSpace(row) - tabular.textVOffset(cell);
5985         int const yend = ybeg + tabular.cellHeight(cell);
5986
5987         if (x < xbeg)
5988                 xx = xbeg - x;
5989         else if (x > xend)
5990                 xx = x - xend;
5991
5992         if (y < ybeg)
5993                 yy = ybeg - y;
5994         else if (y > yend)
5995                 yy = y - yend;
5996
5997         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
5998         //       << " ybeg=" << ybeg << " yend=" << yend
5999         //       << " xx=" << xx << " yy=" << yy
6000         //       << " dist=" << xx + yy << endl;
6001         return xx + yy;
6002 }
6003
6004
6005 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
6006 {
6007         //lyxerr << "InsetTabular::editXY: " << this << endl;
6008         cur.push(*this);
6009         cur.idx() = getNearestCell(cur.bv(), x, y);
6010         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
6011 }
6012
6013
6014 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
6015 {
6016         cur.idx() = getNearestCell(cur.bv(), x, y);
6017         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
6018 }
6019
6020
6021 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
6022 {
6023         idx_type idx_min = 0;
6024         int dist_min = numeric_limits<int>::max();
6025         for (idx_type i = 0, n = nargs(); i != n; ++i) {
6026                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
6027                         int const d = dist(bv, i, x, y);
6028                         if (d < dist_min) {
6029                                 dist_min = d;
6030                                 idx_min = i;
6031                         }
6032                 }
6033         }
6034         return idx_min;
6035 }
6036
6037
6038 int InsetTabular::cellYPos(idx_type const cell) const
6039 {
6040         row_type row = tabular.cellRow(cell);
6041         int ly = 0;
6042         for (row_type r = 0; r < row; ++r)
6043                 ly += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
6044                         + tabular.interRowSpace(r + 1);
6045         return ly;
6046 }
6047
6048
6049 int InsetTabular::cellXPos(idx_type const cell) const
6050 {
6051         col_type col = tabular.cellColumn(cell);
6052         int lx = 0;
6053         for (col_type c = 0; c < col; ++c)
6054                 lx += tabular.column_info[c].width;
6055         return lx;
6056 }
6057
6058
6059 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
6060 {
6061         row_type const row = tabular.cellRow(cur.idx());
6062         col_type const col = tabular.cellColumn(cur.idx());
6063
6064         if (isRightToLeft(cur)) {
6065                 if (tabular.cellColumn(cur.idx()) == 0) {
6066                         if (row == tabular.nrows() - 1)
6067                                 return;
6068                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
6069                 } else {
6070                         if (cur.idx() == 0)
6071                                 return;
6072                         if (col == 0)
6073                                 cur.idx() = tabular.getLastCellInRow(row - 1);
6074                         else
6075                                 cur.idx() = tabular.cellIndex(row, col - 1);
6076                 }
6077         } else {
6078                 if (tabular.isLastCell(cur.idx()))
6079                         return;
6080                 if (cur.idx() == tabular.getLastCellInRow(row))
6081                         cur.idx() = tabular.cellIndex(row + 1, 0);
6082                 else {
6083                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
6084                         cur.idx() = tabular.cellIndex(row, colnextcell);
6085                 }
6086         }
6087
6088         cur.boundary(false);
6089
6090         if (cur.selIsMultiCell()) {
6091                 cur.pit() = cur.lastpit();
6092                 cur.pos() = cur.lastpos();
6093                 return;
6094         }
6095
6096         cur.pit() = 0;
6097         cur.pos() = 0;
6098
6099         // in visual mode, place cursor at extreme left or right
6100
6101         switch(entry_from) {
6102
6103         case ENTRY_DIRECTION_RIGHT:
6104                 cur.posVisToRowExtremity(false /* !left */);
6105                 break;
6106         case ENTRY_DIRECTION_LEFT:
6107                 cur.posVisToRowExtremity(true /* left */);
6108                 break;
6109         case ENTRY_DIRECTION_IGNORE:
6110                 // nothing to do in this case
6111                 break;
6112
6113         }
6114         cur.setCurrentFont();
6115 }
6116
6117
6118 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
6119 {
6120         row_type const row = tabular.cellRow(cur.idx());
6121         col_type const col = tabular.cellColumn(cur.idx());
6122
6123         if (isRightToLeft(cur)) {
6124                 if (cur.idx() == tabular.getLastCellInRow(row)) {
6125                         if (row == 0)
6126                                 return;
6127                         cur.idx() = tabular.getFirstCellInRow(row);
6128                         cur.idx() = tabular.cellAbove(cur.idx());
6129                 } else {
6130                         if (tabular.isLastCell(cur.idx()))
6131                                 return;
6132                         if (cur.idx() == tabular.getLastCellInRow(row))
6133                                 cur.idx() = tabular.cellIndex(row + 1, 0);
6134                         else
6135                                 cur.idx() = tabular.cellIndex(row, col + 1);
6136                 }
6137         } else {
6138                 if (cur.idx() == 0) // first cell
6139                         return;
6140                 if (col == 0)
6141                         cur.idx() = tabular.getLastCellInRow(row - 1);
6142                 else
6143                         cur.idx() = tabular.cellIndex(row, col - 1);
6144         }
6145
6146         if (cur.selIsMultiCell()) {
6147                 cur.pit() = cur.lastpit();
6148                 cur.pos() = cur.lastpos();
6149                 return;
6150         }
6151
6152         cur.pit() = cur.lastpit();
6153         cur.pos() = cur.lastpos();
6154
6155         // in visual mode, place cursor at extreme left or right
6156
6157         switch(entry_from) {
6158
6159         case ENTRY_DIRECTION_RIGHT:
6160                 cur.posVisToRowExtremity(false /* !left */);
6161                 break;
6162         case ENTRY_DIRECTION_LEFT:
6163                 cur.posVisToRowExtremity(true /* left */);
6164                 break;
6165         case ENTRY_DIRECTION_IGNORE:
6166                 // nothing to do in this case
6167                 break;
6168
6169         }
6170         cur.setCurrentFont();
6171 }
6172
6173
6174 void InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
6175 {
6176         cur.recordUndoInset(this);
6177
6178         istringstream is(argument);
6179         // limit the size of strings we read to avoid memory problems
6180         is >> setw(65636);
6181         string s;
6182         // Safe guard.
6183         size_t safe_guard = 0;
6184         for (;;) {
6185                 if (is.eof())
6186                         return;
6187                 safe_guard++;
6188                 if (safe_guard > 1000) {
6189                         LYXERR0("parameter max count reached!");
6190                         return;
6191                 }
6192                 is >> s;
6193                 Tabular::Feature action = Tabular::LAST_ACTION;
6194
6195                 size_t i = 0;
6196                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
6197                         if (s != tabularFeature[i].feature)
6198                                 continue;
6199                         action = tabularFeature[i].action;
6200                         break;
6201                 }
6202                 if (action == Tabular::LAST_ACTION) {
6203                         LYXERR0("Feature not found " << s);
6204                         continue;
6205                 }
6206                 string val;
6207                 if (tabularFeature[i].need_value)
6208                         is >> val;
6209                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
6210                 tabularFeatures(cur, action, val);
6211         }
6212 }
6213
6214
6215 static void checkLongtableSpecial(Tabular::ltType & ltt,
6216                           string const & special, bool & flag)
6217 {
6218         if (special == "dl_above") {
6219                 ltt.topDL = flag;
6220                 ltt.set = false;
6221         } else if (special == "dl_below") {
6222                 ltt.bottomDL = flag;
6223                 ltt.set = false;
6224         } else if (special == "empty") {
6225                 ltt.empty = flag;
6226                 ltt.set = false;
6227         } else if (flag) {
6228                 ltt.empty = false;
6229                 ltt.set = true;
6230         }
6231 }
6232
6233
6234 bool InsetTabular::oneCellHasRotationState(bool rotated,
6235                 row_type row_start, row_type row_end,
6236                 col_type col_start, col_type col_end) const
6237 {
6238         for (row_type r = row_start; r <= row_end; ++r)
6239                 for (col_type c = col_start; c <= col_end; ++c)
6240                         if (rotated) {
6241                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) != 0)
6242                                         return true;
6243                         } else {
6244                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) == 0)
6245                                         return true;
6246                         }
6247         return false;
6248 }
6249
6250
6251 void InsetTabular::tabularFeatures(Cursor & cur,
6252         Tabular::Feature feature, string const & value)
6253 {
6254         col_type sel_col_start;
6255         col_type sel_col_end;
6256         row_type sel_row_start;
6257         row_type sel_row_end;
6258         bool setLines = false;
6259         bool setLinesInnerOnly = false;
6260         LyXAlignment setAlign = LYX_ALIGN_LEFT;
6261         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
6262
6263         switch (feature) {
6264
6265         case Tabular::M_ALIGN_LEFT:
6266         case Tabular::ALIGN_LEFT:
6267                 setAlign = LYX_ALIGN_LEFT;
6268                 break;
6269
6270         case Tabular::M_ALIGN_RIGHT:
6271         case Tabular::ALIGN_RIGHT:
6272                 setAlign = LYX_ALIGN_RIGHT;
6273                 break;
6274
6275         case Tabular::M_ALIGN_CENTER:
6276         case Tabular::ALIGN_CENTER:
6277                 setAlign = LYX_ALIGN_CENTER;
6278                 break;
6279
6280         case Tabular::ALIGN_BLOCK:
6281                 setAlign = LYX_ALIGN_BLOCK;
6282                 break;
6283
6284         case Tabular::ALIGN_DECIMAL:
6285                 setAlign = LYX_ALIGN_DECIMAL;
6286                 break;
6287
6288         case Tabular::M_VALIGN_TOP:
6289         case Tabular::VALIGN_TOP:
6290                 setVAlign = Tabular::LYX_VALIGN_TOP;
6291                 break;
6292
6293         case Tabular::M_VALIGN_BOTTOM:
6294         case Tabular::VALIGN_BOTTOM:
6295                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
6296                 break;
6297
6298         case Tabular::M_VALIGN_MIDDLE:
6299         case Tabular::VALIGN_MIDDLE:
6300                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
6301                 break;
6302
6303         default:
6304                 break;
6305         }
6306
6307         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
6308         row_type const row = tabular.cellRow(cur.idx());
6309         col_type const column = tabular.cellColumn(cur.idx());
6310         bool flag = true;
6311         Tabular::ltType ltt;
6312
6313         switch (feature) {
6314
6315         case Tabular::SET_TABULAR_WIDTH:
6316                 tabular.setTabularWidth(Length(value));
6317                 break;
6318
6319         case Tabular::SET_PWIDTH: {
6320                 Length const len(value);
6321                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
6322                         tabular.setColumnPWidth(cur, tabular.cellIndex(row, c), len);
6323                         if (len.zero()
6324                             && tabular.getAlignment(tabular.cellIndex(row, c), true) == LYX_ALIGN_BLOCK)
6325                                 tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
6326                 }
6327                 break;
6328         }
6329
6330         case Tabular::SET_MPWIDTH:
6331                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
6332                 break;
6333
6334         case Tabular::TOGGLE_VARWIDTH_COLUMN: {
6335                 bool const varwidth = value == "on";
6336                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6337                         tabular.toggleVarwidth(tabular.cellIndex(row, c), varwidth);
6338                 break;
6339         }
6340
6341         case Tabular::SET_MROFFSET:
6342                 tabular.setMROffset(cur, cur.idx(), Length(value));
6343                 break;
6344
6345         case Tabular::SET_SPECIAL_COLUMN:
6346         case Tabular::SET_SPECIAL_MULTICOLUMN:
6347                 if (value == "none")
6348                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
6349                 else
6350                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
6351                 break;
6352
6353         case Tabular::APPEND_ROW:
6354                 // append the row into the tabular
6355                 tabular.appendRow(row);
6356                 break;
6357
6358         case Tabular::APPEND_COLUMN:
6359                 // append the column into the tabular
6360                 tabular.appendColumn(column);
6361                 cur.idx() = tabular.cellIndex(row, column);
6362                 break;
6363
6364         case Tabular::DELETE_ROW:
6365                 if (sel_row_end == tabular.nrows() - 1 && sel_row_start != 0) {
6366                         for (col_type c = 0; c < tabular.ncols(); c++) {
6367                                 tabular.setBottomLine(tabular.cellIndex(sel_row_start - 1, c),
6368                                         tabular.bottomLine(tabular.cellIndex(sel_row_end, c)));
6369                                 tabular.setBottomLineTrim(tabular.cellIndex(sel_row_start - 1, c),
6370                                         tabular.bottomLineTrim(tabular.cellIndex(sel_row_end, c)));
6371                         }
6372                 }
6373
6374                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6375                         tabular.deleteRow(sel_row_start);
6376                 if (sel_row_start >= tabular.nrows())
6377                         --sel_row_start;
6378                 cur.idx() = tabular.cellIndex(sel_row_start, column);
6379                 cur.pit() = 0;
6380                 cur.pos() = 0;
6381                 cur.selection(false);
6382                 break;
6383
6384         case Tabular::DELETE_COLUMN:
6385                 if (sel_col_end == tabular.ncols() - 1 && sel_col_start != 0) {
6386                         for (row_type r = 0; r < tabular.nrows(); r++)
6387                                 tabular.setRightLine(tabular.cellIndex(r, sel_col_start - 1),
6388                                         tabular.rightLine(tabular.cellIndex(r, sel_col_end)));
6389                 }
6390
6391                 if (sel_col_start == 0 && sel_col_end != tabular.ncols() - 1) {
6392                         for (row_type r = 0; r < tabular.nrows(); r++)
6393                                 tabular.setLeftLine(tabular.cellIndex(r, sel_col_end + 1),
6394                                         tabular.leftLine(tabular.cellIndex(r, 0)));
6395                 }
6396
6397                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6398                         tabular.deleteColumn(sel_col_start);
6399                 if (sel_col_start >= tabular.ncols())
6400                         --sel_col_start;
6401                 cur.idx() = tabular.cellIndex(row, sel_col_start);
6402                 cur.pit() = 0;
6403                 cur.pos() = 0;
6404                 cur.selection(false);
6405                 break;
6406
6407         case Tabular::COPY_ROW:
6408                 tabular.copyRow(row);
6409                 break;
6410
6411         case Tabular::COPY_COLUMN:
6412                 tabular.copyColumn(column);
6413                 cur.idx() = tabular.cellIndex(row, column);
6414                 break;
6415
6416         case Tabular::MOVE_COLUMN_RIGHT:
6417                 tabular.moveColumn(column, Tabular::RIGHT);
6418                 cur.idx() = tabular.cellIndex(row, column + 1);
6419                 break;
6420
6421         case Tabular::MOVE_COLUMN_LEFT:
6422                 tabular.moveColumn(column, Tabular::LEFT);
6423                 cur.idx() = tabular.cellIndex(row, column - 1);
6424                 break;
6425
6426         case Tabular::MOVE_ROW_DOWN:
6427                 tabular.moveRow(row, Tabular::DOWN);
6428                 cur.idx() = tabular.cellIndex(row + 1, column);
6429                 break;
6430
6431         case Tabular::MOVE_ROW_UP:
6432                 tabular.moveRow(row, Tabular::UP);
6433                 cur.idx() = tabular.cellIndex(row - 1, column);
6434                 break;
6435
6436         case Tabular::SET_LINE_TOP:
6437         case Tabular::TOGGLE_LINE_TOP: {
6438                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
6439                                ? (value == "true") : !tabular.topLine(cur.idx());
6440                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6441                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6442                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
6443                 break;
6444         }
6445
6446         case Tabular::SET_LINE_BOTTOM:
6447         case Tabular::TOGGLE_LINE_BOTTOM: {
6448                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
6449                                ? (value == "true") : !tabular.bottomLine(cur.idx());
6450                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6451                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6452                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
6453                 break;
6454         }
6455
6456         case Tabular::SET_LTRIM_TOP:
6457         case Tabular::TOGGLE_LTRIM_TOP: {
6458                 bool l = (feature == Tabular::SET_LTRIM_TOP)
6459                                ? (value == "true") : !tabular.topLineTrim(cur.idx()).first;
6460                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6461                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6462                                 tabular.setTopLineLTrim(tabular.cellIndex(r, c), l);
6463                 break;
6464         }
6465
6466         case Tabular::SET_RTRIM_TOP:
6467         case Tabular::TOGGLE_RTRIM_TOP: {
6468                 bool l = (feature == Tabular::SET_RTRIM_TOP)
6469                                ? (value == "true") : !tabular.topLineTrim(cur.idx()).second;
6470                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6471                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6472                                 tabular.setTopLineRTrim(tabular.cellIndex(r, c), l);
6473                 break;
6474         }
6475
6476         case Tabular::SET_LTRIM_BOTTOM:
6477         case Tabular::TOGGLE_LTRIM_BOTTOM: {
6478                 bool l = (feature == Tabular::SET_LTRIM_BOTTOM)
6479                                ? (value == "true") : !tabular.bottomLineTrim(cur.idx()).first;
6480                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6481                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6482                                 tabular.setBottomLineLTrim(tabular.cellIndex(r, c), l);
6483                 break;
6484         }
6485
6486         case Tabular::SET_RTRIM_BOTTOM:
6487         case Tabular::TOGGLE_RTRIM_BOTTOM: {
6488                 bool l = (feature == Tabular::SET_RTRIM_BOTTOM)
6489                                ? (value == "true") : !tabular.bottomLineTrim(cur.idx()).second;
6490                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6491                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6492                                 tabular.setBottomLineRTrim(tabular.cellIndex(r, c), l);
6493                 break;
6494         }
6495
6496         case Tabular::SET_LINE_LEFT:
6497         case Tabular::TOGGLE_LINE_LEFT: {
6498                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
6499                                ? (value == "true") : !tabular.leftLine(cur.idx());
6500                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6501                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6502                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
6503                 break;
6504         }
6505
6506         case Tabular::SET_LINE_RIGHT:
6507         case Tabular::TOGGLE_LINE_RIGHT: {
6508                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
6509                                ? (value == "true") : !tabular.rightLine(cur.idx());
6510                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6511                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6512                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
6513                 break;
6514         }
6515
6516         case Tabular::M_ALIGN_LEFT:
6517         case Tabular::M_ALIGN_RIGHT:
6518         case Tabular::M_ALIGN_CENTER:
6519         case Tabular::ALIGN_LEFT:
6520         case Tabular::ALIGN_RIGHT:
6521         case Tabular::ALIGN_CENTER:
6522         case Tabular::ALIGN_BLOCK:
6523         case Tabular::ALIGN_DECIMAL:
6524                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6525                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6526                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign,
6527                                 !tabular.getPWidth(c).zero());
6528                 break;
6529
6530         case Tabular::M_VALIGN_TOP:
6531         case Tabular::M_VALIGN_BOTTOM:
6532         case Tabular::M_VALIGN_MIDDLE:
6533                 flag = false;
6534                 // fall through
6535         case Tabular::VALIGN_TOP:
6536         case Tabular::VALIGN_BOTTOM:
6537         case Tabular::VALIGN_MIDDLE:
6538                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6539                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6540                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
6541                 break;
6542
6543         case Tabular::SET_MULTICOLUMN: {
6544                 if (!cur.selection()) {
6545                         // just multicol for one single cell
6546                         // check whether we are completely in a multicol
6547                         if (!tabular.isMultiColumn(cur.idx()))
6548                                 tabular.setMultiColumn(cur, cur.idx(), 1,
6549                                         tabular.rightLine(cur.idx()));
6550                         break;
6551                 }
6552                 // we have a selection so this means we just add all these
6553                 // cells to form a multicolumn cell
6554                 idx_type const s_start = cur.selBegin().idx();
6555                 row_type const col_start = tabular.cellColumn(s_start);
6556                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
6557                 cur.idx() = tabular.setMultiColumn(cur, s_start, col_end - col_start + 1,
6558                                                    tabular.rightLine(cur.selEnd().idx()));
6559                 cur.pit() = 0;
6560                 cur.pos() = 0;
6561                 cur.selection(false);
6562                 break;
6563         }
6564
6565         case Tabular::UNSET_MULTICOLUMN: {
6566                 if (!cur.selection()) {
6567                         if (tabular.isMultiColumn(cur.idx()))
6568                                 tabular.unsetMultiColumn(cur.idx());
6569                 }
6570                 break;
6571         }
6572
6573         case Tabular::MULTICOLUMN: {
6574                 if (!cur.selection()) {
6575                         if (tabular.isMultiColumn(cur.idx()))
6576                                 tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
6577                         else
6578                                 tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
6579                         break;
6580                 }
6581                 bool merge = false;
6582                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
6583                         row_type const r = sel_row_start;
6584                         if (!tabular.isMultiColumn(tabular.cellIndex(r, c))
6585                             || (r > sel_row_start && !tabular.isPartOfMultiColumn(r, c)))
6586                                 merge = true;
6587                 }
6588                 // If the selection contains at least one singlecol cell
6589                 // or multiple multicol cells,
6590                 // we assume the user will merge is to a single multicol
6591                 if (merge)
6592                         tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
6593                 else
6594                         tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
6595                 break;
6596         }
6597
6598         case Tabular::SET_MULTIROW: {
6599                 if (!cur.selection()) {
6600                         // just multirow for one single cell
6601                         // check whether we are completely in a multirow
6602                         if (!tabular.isMultiRow(cur.idx()))
6603                                 tabular.setMultiRow(cur, cur.idx(), 1,
6604                                                     tabular.bottomLine(cur.idx()),
6605                                                     tabular.getAlignment(cur.idx()));
6606                         break;
6607                 }
6608                 // we have a selection so this means we just add all this
6609                 // cells to form a multirow cell
6610                 idx_type const s_start = cur.selBegin().idx();
6611                 row_type const row_start = tabular.cellRow(s_start);
6612                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
6613                 cur.idx() = tabular.setMultiRow(cur, s_start, row_end - row_start + 1,
6614                                                 tabular.bottomLine(cur.selEnd().idx()),
6615                                                 tabular.getAlignment(cur.selEnd().idx()));
6616                 cur.pit() = 0;
6617                 cur.pos() = 0;
6618                 cur.selection(false);
6619                 break;
6620         }
6621
6622         case Tabular::UNSET_MULTIROW: {
6623                 if (!cur.selection()) {
6624                         if (tabular.isMultiRow(cur.idx()))
6625                                 tabular.unsetMultiRow(cur.idx());
6626                 }
6627                 break;
6628         }
6629
6630         case Tabular::MULTIROW: {
6631                 if (!cur.selection()) {
6632                         if (tabular.isMultiRow(cur.idx()))
6633                                 tabularFeatures(cur, Tabular::UNSET_MULTIROW);
6634                         else
6635                                 tabularFeatures(cur, Tabular::SET_MULTIROW);
6636                         break;
6637                 }
6638                 bool merge = false;
6639                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6640                         col_type const c = sel_col_start;
6641                         if (!tabular.isMultiRow(tabular.cellIndex(r, c))
6642                             || (r > sel_row_start && !tabular.isPartOfMultiRow(r, c)))
6643                                 merge = true;
6644                 }
6645                 // If the selection contains at least one singlerow cell
6646                 // or multiple multirow cells,
6647                 // we assume the user will merge is to a single multirow
6648                 if (merge)
6649                         tabularFeatures(cur, Tabular::SET_MULTIROW);
6650                 else
6651                         tabularFeatures(cur, Tabular::UNSET_MULTIROW);
6652                 break;
6653         }
6654
6655         case Tabular::SET_INNER_LINES:
6656                 setLinesInnerOnly = true;
6657                 // fall through
6658         case Tabular::SET_ALL_LINES:
6659                 setLines = true;
6660                 // fall through
6661         case Tabular::UNSET_ALL_LINES:
6662                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6663                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
6664                                 idx_type const cell = tabular.cellIndex(r, c);
6665                                 if (!setLinesInnerOnly || r != sel_row_start)
6666                                         tabular.setTopLine(cell, setLines);
6667                                 if ((!setLinesInnerOnly || r != sel_row_end)
6668                                     && (!setLines || r == sel_row_end))
6669                                         tabular.setBottomLine(cell, setLines);
6670                                 if ((!setLinesInnerOnly || c != sel_col_end)
6671                                     && (!setLines || c == sel_col_end))
6672                                         tabular.setRightLine(cell, setLines);
6673                                 if ((!setLinesInnerOnly || c != sel_col_start))
6674                                         tabular.setLeftLine(cell, setLines);
6675                         }
6676                 break;
6677
6678         case Tabular::RESET_FORMAL_DEFAULT:
6679                 for (row_type r = 0; r < tabular.nrows(); ++r) {
6680                         bool const head_or_foot = r == 0 || r == tabular.nrows() - 1;
6681                         for (col_type c = 0; c < tabular.ncols(); ++c) {
6682                                 idx_type const cell = tabular.cellIndex(r, c);
6683                                 tabular.setTopLine(cell, head_or_foot);
6684                                 tabular.setBottomLine(cell, head_or_foot);
6685                         }
6686                 }
6687                 break;
6688
6689         case Tabular::SET_BORDER_LINES:
6690                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6691                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
6692                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
6693                 }
6694                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
6695                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
6696                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
6697                 }
6698                 break;
6699
6700         case Tabular::TOGGLE_LONGTABULAR:
6701                 if (tabular.is_long_tabular)
6702                         tabularFeatures(cur, Tabular::UNSET_LONGTABULAR);
6703                 else
6704                         tabular.is_long_tabular = true;
6705                 break;
6706
6707         case Tabular::SET_LONGTABULAR:
6708                 tabular.is_long_tabular = true;
6709                 break;
6710
6711         case Tabular::UNSET_LONGTABULAR:
6712                 for (row_type r = 0; r < tabular.nrows(); ++r) {
6713                         if (tabular.ltCaption(r)) {
6714                                 cur.idx() = tabular.cellIndex(r, 0);
6715                                 cur.pit() = 0;
6716                                 cur.pos() = 0;
6717                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
6718                         }
6719                 }
6720                 tabular.is_long_tabular = false;
6721                 break;
6722
6723         case Tabular::SET_ROTATE_TABULAR:
6724                 tabular.rotate = convert<int>(value);
6725                 break;
6726
6727         case Tabular::UNSET_ROTATE_TABULAR:
6728                 tabular.rotate = 0;
6729                 break;
6730
6731         case Tabular::TOGGLE_ROTATE_TABULAR:
6732                 // when pressing the rotate button we default to 90° rotation
6733                 tabular.rotate != 0 ? tabular.rotate = 0 : tabular.rotate = 90;
6734                 break;
6735
6736         case Tabular::TABULAR_VALIGN_TOP:
6737                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
6738                 break;
6739
6740         case Tabular::TABULAR_VALIGN_MIDDLE:
6741                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
6742                 break;
6743
6744         case Tabular::TABULAR_VALIGN_BOTTOM:
6745                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
6746                 break;
6747
6748         case Tabular::LONGTABULAR_ALIGN_LEFT:
6749                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
6750                 break;
6751
6752         case Tabular::LONGTABULAR_ALIGN_CENTER:
6753                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
6754                 break;
6755
6756         case Tabular::LONGTABULAR_ALIGN_RIGHT:
6757                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
6758                 break;
6759
6760         case Tabular::SET_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), convert<int>(value));
6764                 break;
6765
6766         case Tabular::UNSET_ROTATE_CELL:
6767                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6768                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6769                                 tabular.setRotateCell(tabular.cellIndex(r, c), 0);
6770                 break;
6771
6772         case Tabular::TOGGLE_ROTATE_CELL:
6773                 {
6774                 bool oneNotRotated = oneCellHasRotationState(false,
6775                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
6776
6777                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6778                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
6779                                 // when pressing the rotate cell button we default to 90° rotation
6780                                 if (oneNotRotated)
6781                                         tabular.setRotateCell(tabular.cellIndex(r, c), 90);
6782                                 else
6783                                         tabular.setRotateCell(tabular.cellIndex(r, c), 0);
6784                         }
6785                 }
6786                 break;
6787
6788         case Tabular::SET_USEBOX: {
6789                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
6790                 if (val == tabular.getUsebox(cur.idx()))
6791                         val = Tabular::BOX_NONE;
6792                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6793                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6794                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
6795                 break;
6796         }
6797
6798         case Tabular::UNSET_LTFIRSTHEAD:
6799                 flag = false;
6800                 // fall through
6801         case Tabular::SET_LTFIRSTHEAD:
6802                 tabular.getRowOfLTFirstHead(row, ltt);
6803                 checkLongtableSpecial(ltt, value, flag);
6804                 tabular.setLTHead(row, flag, ltt, true);
6805                 break;
6806
6807         case Tabular::UNSET_LTHEAD:
6808                 flag = false;
6809                 // fall through
6810         case Tabular::SET_LTHEAD:
6811                 tabular.getRowOfLTHead(row, ltt);
6812                 checkLongtableSpecial(ltt, value, flag);
6813                 tabular.setLTHead(row, flag, ltt, false);
6814                 break;
6815
6816         case Tabular::UNSET_LTFOOT:
6817                 flag = false;
6818                 // fall through
6819         case Tabular::SET_LTFOOT:
6820                 tabular.getRowOfLTFoot(row, ltt);
6821                 checkLongtableSpecial(ltt, value, flag);
6822                 tabular.setLTFoot(row, flag, ltt, false);
6823                 break;
6824
6825         case Tabular::UNSET_LTLASTFOOT:
6826                 flag = false;
6827                 // fall through
6828         case Tabular::SET_LTLASTFOOT:
6829                 tabular.getRowOfLTLastFoot(row, ltt);
6830                 checkLongtableSpecial(ltt, value, flag);
6831                 tabular.setLTFoot(row, flag, ltt, true);
6832                 break;
6833
6834         case Tabular::UNSET_LTNEWPAGE:
6835                 flag = false;
6836                 // fall through
6837         case Tabular::SET_LTNEWPAGE:
6838                 tabular.setLTNewPage(row, flag);
6839                 break;
6840
6841         case Tabular::SET_LTCAPTION: {
6842                 if (tabular.ltCaption(row))
6843                         break;
6844                 cur.idx() = tabular.setLTCaption(cur, row, true);
6845                 cur.pit() = 0;
6846                 cur.pos() = 0;
6847                 cur.selection(false);
6848                 // If a row is set as caption, then also insert
6849                 // a caption. Otherwise the LaTeX output is broken.
6850                 // Select cell if it is non-empty
6851                 if (cur.lastpos() > 0 || cur.lastpit() > 0)
6852                         lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
6853                 lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
6854                 break;
6855         }
6856
6857         case Tabular::UNSET_LTCAPTION: {
6858                 if (!tabular.ltCaption(row))
6859                         break;
6860                 cur.idx() = tabular.setLTCaption(cur, row, false);
6861                 cur.pit() = 0;
6862                 cur.pos() = 0;
6863                 cur.selection(false);
6864                 FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
6865                 if (lyx::getStatus(fr).enabled())
6866                         lyx::dispatch(fr);
6867                 break;
6868         }
6869
6870         case Tabular::TOGGLE_LTCAPTION: {
6871                 if (tabular.ltCaption(row))
6872                         tabularFeatures(cur, Tabular::UNSET_LTCAPTION);
6873                 else
6874                         tabularFeatures(cur, Tabular::SET_LTCAPTION);
6875                 break;
6876         }
6877
6878         case Tabular::TOGGLE_BOOKTABS:
6879                 tabular.use_booktabs = !tabular.use_booktabs;
6880                 break;
6881
6882         case Tabular::SET_BOOKTABS:
6883                 tabular.use_booktabs = true;
6884                 break;
6885
6886         case Tabular::UNSET_BOOKTABS:
6887                 tabular.use_booktabs = false;
6888                 break;
6889
6890         case Tabular::SET_TOP_SPACE: {
6891                 Length len;
6892                 if (value == "default")
6893                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6894                                 tabular.row_info[r].top_space_default = true;
6895                 else if (value == "none")
6896                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6897                                 tabular.row_info[r].top_space_default = false;
6898                                 tabular.row_info[r].top_space = len;
6899                         }
6900                 else if (isValidLength(value, &len))
6901                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6902                                 tabular.row_info[r].top_space_default = false;
6903                                 tabular.row_info[r].top_space = len;
6904                         }
6905                 break;
6906         }
6907
6908         case Tabular::SET_BOTTOM_SPACE: {
6909                 Length len;
6910                 if (value == "default")
6911                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6912                                 tabular.row_info[r].bottom_space_default = true;
6913                 else if (value == "none")
6914                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6915                                 tabular.row_info[r].bottom_space_default = false;
6916                                 tabular.row_info[r].bottom_space = len;
6917                         }
6918                 else if (isValidLength(value, &len))
6919                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6920                                 tabular.row_info[r].bottom_space_default = false;
6921                                 tabular.row_info[r].bottom_space = len;
6922                         }
6923                 break;
6924         }
6925
6926         case Tabular::SET_INTERLINE_SPACE: {
6927                 Length len;
6928                 if (value == "default")
6929                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6930                                 tabular.row_info[r].interline_space_default = true;
6931                 else if (value == "none")
6932                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6933                                 tabular.row_info[r].interline_space_default = false;
6934                                 tabular.row_info[r].interline_space = len;
6935                         }
6936                 else if (isValidLength(value, &len))
6937                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6938                                 tabular.row_info[r].interline_space_default = false;
6939                                 tabular.row_info[r].interline_space = len;
6940                         }
6941                 break;
6942         }
6943
6944         case Tabular::SET_DECIMAL_POINT:
6945                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6946                         tabular.column_info[c].decimal_point = from_utf8(value);
6947                 break;
6948
6949         // dummy stuff just to avoid warnings
6950         case Tabular::LAST_ACTION:
6951                 break;
6952         }
6953 }
6954
6955
6956 bool InsetTabular::copySelection(Cursor & cur)
6957 {
6958         if (!cur.selection())
6959                 return false;
6960
6961         row_type rs, re;
6962         col_type cs, ce;
6963         getSelection(cur, rs, re, cs, ce);
6964
6965         paste_tabular.reset(new Tabular(tabular));
6966
6967         for (row_type r = 0; r < rs; ++r)
6968                 paste_tabular->deleteRow(0);
6969
6970         row_type const rows = re - rs + 1;
6971         while (paste_tabular->nrows() > rows)
6972                 paste_tabular->deleteRow(rows);
6973
6974         for (col_type c = 0; c < cs; ++c)
6975                 paste_tabular->deleteColumn(0);
6976
6977         col_type const columns = ce - cs + 1;
6978         while (paste_tabular->ncols() > columns)
6979                 paste_tabular->deleteColumn(columns);
6980
6981         paste_tabular->setBuffer(tabular.buffer());
6982
6983         odocstringstream os;
6984         OutputParams const runparams(0);
6985         paste_tabular->plaintext(os, runparams, 0, true, '\t', INT_MAX);
6986         // Needed for the "Edit->Paste recent" menu and the system clipboard.
6987         cap::copySelection(cur, os.str());
6988
6989         // mark tabular stack dirty
6990         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
6991         // when we (hopefully) have a one-for-all paste mechanism.
6992         // This must be called after cap::copySelection.
6993         dirtyTabularStack(true);
6994
6995         return true;
6996 }
6997
6998
6999 bool InsetTabular::pasteClipboard(Cursor & cur)
7000 {
7001         if (!paste_tabular)
7002                 return false;
7003         col_type actcol = tabular.cellColumn(cur.idx());
7004         row_type actrow = tabular.cellRow(cur.idx());
7005
7006         if (cur.selIsMultiCell()) {
7007                 row_type re;
7008                 col_type ce;
7009                 getSelection(cur, actrow, re, actcol, ce);
7010         }
7011
7012         for (row_type r1 = 0, r2 = actrow;
7013              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
7014              ++r1, ++r2) {
7015                 for (col_type c1 = 0, c2 = actcol;
7016                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
7017                     ++c1, ++c2) {
7018                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
7019                               tabular.isPartOfMultiColumn(r2, c2))
7020                                 continue;
7021                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
7022                                 --c2;
7023                                 continue;
7024                         }
7025                         if (tabular.isPartOfMultiColumn(r2, c2)) {
7026                                 --c1;
7027                                 continue;
7028                         }
7029                         shared_ptr<InsetTableCell> inset(
7030                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
7031                         tabular.setCellInset(r2, c2, inset);
7032                         // FIXME?: why do we need to do this explicitly? (EL)
7033                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
7034
7035                         // FIXME: change tracking (MG)
7036                         inset->setChange(Change(buffer().params().track_changes ?
7037                                                 Change::INSERTED : Change::UNCHANGED));
7038                         cur.pos() = 0;
7039                         cur.pit() = 0;
7040                 }
7041         }
7042         return true;
7043 }
7044
7045
7046 void InsetTabular::cutSelection(Cursor & cur)
7047 {
7048         if (!cur.selection())
7049                 return;
7050
7051         row_type rs, re;
7052         col_type cs, ce;
7053         getSelection(cur, rs, re, cs, ce);
7054         for (row_type r = rs; r <= re; ++r) {
7055                 for (col_type c = cs; c <= ce; ++c) {
7056                         shared_ptr<InsetTableCell> t
7057                                 = cell(tabular.cellIndex(r, c));
7058                         if (buffer().params().track_changes)
7059                                 // FIXME: Change tracking (MG)
7060                                 t->setChange(Change(Change::DELETED));
7061                         else
7062                                 t->clear();
7063                 }
7064         }
7065
7066         // cursor position might be invalid now
7067         if (cur.pit() > cur.lastpit())
7068                 cur.pit() = cur.lastpit();
7069         if (cur.pos() > cur.lastpos())
7070                 cur.pos() = cur.lastpos();
7071         cur.clearSelection();
7072 }
7073
7074
7075 bool InsetTabular::isRightToLeft(Cursor & cur) const
7076 {
7077         // LASSERT: It might be better to abandon this Buffer.
7078         LASSERT(cur.depth() > 1, return false);
7079         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
7080         pos_type const parentpos = cur[cur.depth() - 2].pos();
7081         return parentpar.getFontSettings(buffer().params(),
7082                                          parentpos).language()->rightToLeft();
7083 }
7084
7085
7086 docstring InsetTabular::asString(idx_type stidx, idx_type enidx,
7087                                  bool intoInsets)
7088 {
7089         LASSERT(stidx <= enidx, return docstring());
7090         docstring retval;
7091         col_type const col1 = tabular.cellColumn(stidx);
7092         col_type const col2 = tabular.cellColumn(enidx);
7093         row_type const row1 = tabular.cellRow(stidx);
7094         row_type const row2 = tabular.cellRow(enidx);
7095         bool first = true;
7096         for (col_type col = col1; col <= col2; col++)
7097                 for (row_type row = row1; row <= row2; row++) {
7098                         if (!first)
7099                                 retval += "\n";
7100                         else
7101                                 first = false;
7102                         retval += tabular.cellInset(row, col)->asString(intoInsets);
7103                 }
7104         return retval;
7105 }
7106
7107
7108 void InsetTabular::getSelection(Cursor & cur,
7109         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
7110 {
7111         CursorSlice const & beg = cur.selBegin();
7112         CursorSlice const & end = cur.selEnd();
7113         cs = tabular.cellColumn(beg.idx());
7114         ce = tabular.cellColumn(end.idx());
7115         if (cs > ce)
7116                 swap(cs, ce);
7117
7118         rs = tabular.cellRow(beg.idx());
7119         re = tabular.cellRow(end.idx());
7120         if (rs > re)
7121                 swap(rs, re);
7122 }
7123
7124
7125 Text * InsetTabular::getText(int idx) const
7126 {
7127         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
7128 }
7129
7130
7131 bool InsetTabular::isChanged() const
7132 {
7133         for (idx_type idx = 0; idx < nargs(); ++idx)
7134                 if (cell(idx)->isChanged())
7135                         return true;
7136         // FIXME: shall we look at row/columns changed status?
7137         return false;
7138 }
7139
7140
7141 void InsetTabular::setChange(Change const & change)
7142 {
7143         for (idx_type idx = 0; idx < nargs(); ++idx)
7144                 cell(idx)->setChange(change);
7145 }
7146
7147
7148 void InsetTabular::acceptChanges()
7149 {
7150         for (idx_type idx = 0; idx < nargs(); ++idx)
7151                 cell(idx)->acceptChanges();
7152         for (row_type row = 0; row < tabular.nrows(); ++row) {
7153                 if (tabular.row_info[row].change == Change::INSERTED)
7154                         tabular.row_info[row].change = Change::UNCHANGED;
7155                 else if (tabular.row_info[row].change == Change::DELETED)
7156                         tabular.deleteRow(row, true);
7157         }
7158         for (col_type col = 0; col < tabular.ncols(); ++col) {
7159                 if (tabular.column_info[col].change == Change::INSERTED)
7160                         tabular.column_info[col].change = Change::UNCHANGED;
7161                 else if (tabular.column_info[col].change == Change::DELETED)
7162                         tabular.deleteColumn(col, true);
7163         }
7164 }
7165
7166
7167 void InsetTabular::rejectChanges()
7168 {
7169         for (idx_type idx = 0; idx < nargs(); ++idx)
7170                 cell(idx)->rejectChanges();
7171         for (row_type row = 0; row < tabular.nrows(); ++row) {
7172                 if (tabular.row_info[row].change == Change::DELETED)
7173                         tabular.row_info[row].change = Change::UNCHANGED;
7174                 else if (tabular.row_info[row].change == Change::INSERTED)
7175                         tabular.deleteRow(row, true);
7176         }
7177         for (col_type col = 0; col < tabular.ncols(); ++col) {
7178                 if (tabular.column_info[col].change == Change::DELETED)
7179                         tabular.column_info[col].change = Change::UNCHANGED;
7180                 else if (tabular.column_info[col].change == Change::INSERTED)
7181                         tabular.deleteColumn(col, true);
7182         }
7183 }
7184
7185
7186 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
7187 {
7188         return tabular.getPWidth(cell).zero();
7189 }
7190
7191
7192 bool InsetTabular::forcePlainLayout(idx_type cell) const
7193 {
7194         return tabular.isMultiColumn(cell) && !tabular.getPWidth(cell).zero();
7195 }
7196
7197
7198 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
7199                                      bool usePaste)
7200 {
7201         if (buf.length() <= 0)
7202                 return true;
7203
7204         col_type cols = 1;
7205         row_type rows = 1;
7206         col_type maxCols = 1;
7207         size_t const len = buf.length();
7208         size_t p = 0;
7209
7210         while (p < len &&
7211                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
7212                 switch (buf[p]) {
7213                 case '\t':
7214                         ++cols;
7215                         break;
7216                 case '\n':
7217                         if (p + 1 < len)
7218                                 ++rows;
7219                         maxCols = max(cols, maxCols);
7220                         cols = 1;
7221                         break;
7222                 }
7223                 ++p;
7224         }
7225         maxCols = max(cols, maxCols);
7226         Tabular * loctab;
7227         idx_type cell = 0;
7228         col_type ocol = 0;
7229         row_type row = 0;
7230         if (usePaste) {
7231                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
7232                 loctab = paste_tabular.get();
7233                 dirtyTabularStack(true);
7234         } else {
7235                 loctab = &tabular;
7236                 cell = bv.cursor().idx();
7237                 ocol = tabular.cellColumn(cell);
7238                 row = tabular.cellRow(cell);
7239         }
7240
7241         size_t op = 0;
7242         idx_type cells = loctab->numberofcells;
7243         p = 0;
7244         cols = ocol;
7245         rows = loctab->nrows();
7246         col_type columns = loctab->ncols();
7247
7248         while (p < len &&
7249                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
7250         {
7251                 if (p >= len)
7252                         break;
7253                 switch (buf[p]) {
7254                 case '\t':
7255                         // append column if necessary
7256                         if (cols == columns) {
7257                                 loctab->appendColumn(cols - 1);
7258                                 columns = loctab->ncols();
7259                                 cells = loctab->numberofcells;
7260                                 ++cell;
7261                         }
7262                         if (cols < columns) {
7263                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
7264                                 Font const font = bv.textMetrics(&inset->text()).
7265                                         displayFont(0, 0);
7266                                 inset->setText(buf.substr(op, p - op), font,
7267                                                buffer().params().track_changes);
7268                                 ++cols;
7269                                 ++cell;
7270                         }
7271                         break;
7272                 case '\n':
7273                         // we can only set this if we are not too far right
7274                         if (cols < columns) {
7275                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
7276                                 Font const font = bv.textMetrics(&inset->text()).
7277                                         displayFont(0, 0);
7278                                 inset->setText(buf.substr(op, p - op), font,
7279                                                buffer().params().track_changes);
7280                         }
7281                         cols = ocol;
7282                         ++row;
7283                         // append row if necessary
7284                         if (row == rows && p < len - 1) {
7285                                 loctab->appendRow(row - 1);
7286                                 rows = loctab->nrows();
7287                                 cells = loctab->numberofcells;
7288                         }
7289                         if (row < rows)
7290                                 cell = loctab->cellIndex(row, cols);
7291                         break;
7292                 }
7293                 ++p;
7294                 op = p;
7295         }
7296         // check for the last cell if there is no trailing '\n'
7297         if (cell < cells && op < len) {
7298                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
7299                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
7300                 inset->setText(buf.substr(op, len - op), font,
7301                         buffer().params().track_changes);
7302         }
7303         return true;
7304 }
7305
7306
7307 void InsetTabular::addPreview(DocIterator const & inset_pos,
7308         PreviewLoader & loader) const
7309 {
7310         DocIterator cell_pos = inset_pos;
7311
7312         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
7313         for (row_type r = 0; r < tabular.nrows(); ++r) {
7314                 for (col_type c = 0; c < tabular.ncols(); ++c) {
7315                         cell_pos.top().idx() = tabular.cellIndex(r, c);
7316                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
7317                 }
7318         }
7319 }
7320
7321
7322 bool InsetTabular::completionSupported(Cursor const & cur) const
7323 {
7324         Cursor const & bvCur = cur.bv().cursor();
7325         if (&bvCur.inset() != this)
7326                 return false;
7327         return cur.text()->completionSupported(cur);
7328 }
7329
7330
7331 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
7332 {
7333         return completionSupported(cur);
7334 }
7335
7336
7337 bool InsetTabular::automaticInlineCompletion() const
7338 {
7339         return lyxrc.completion_inline_text;
7340 }
7341
7342
7343 bool InsetTabular::automaticPopupCompletion() const
7344 {
7345         return lyxrc.completion_popup_text;
7346 }
7347
7348
7349 bool InsetTabular::showCompletionCursor() const
7350 {
7351         return lyxrc.completion_cursor_text;
7352 }
7353
7354
7355 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
7356 {
7357         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
7358 }
7359
7360
7361 docstring InsetTabular::completionPrefix(Cursor const & cur) const
7362 {
7363         if (!completionSupported(cur))
7364                 return docstring();
7365         return cur.text()->completionPrefix(cur);
7366 }
7367
7368
7369 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
7370 {
7371         if (!completionSupported(cur))
7372                 return false;
7373
7374         return cur.text()->insertCompletion(cur, s, finished);
7375 }
7376
7377
7378 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y,
7379                                     Dimension & dim) const
7380 {
7381         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
7382         tm.completionPosAndDim(cur, x, y, dim);
7383 }
7384
7385
7386 void InsetTabular::string2params(string const & in, InsetTabular & inset)
7387 {
7388         istringstream data(in);
7389         Lexer lex;
7390         lex.setStream(data);
7391
7392         if (in.empty())
7393                 return;
7394
7395         string token;
7396         lex >> token;
7397         if (!lex || token != "tabular") {
7398                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
7399                 return;
7400         }
7401
7402         // This is part of the inset proper that is usually swallowed
7403         // by Buffer::readInset
7404         lex >> token;
7405         if (!lex || token != "Tabular") {
7406                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
7407                 return;
7408         }
7409
7410         inset.read(lex);
7411 }
7412
7413
7414 string InsetTabular::params2string(InsetTabular const & inset)
7415 {
7416         ostringstream data;
7417         data << "tabular" << ' ';
7418         inset.write(data);
7419         data << "\\end_inset\n";
7420         return data.str();
7421 }
7422
7423
7424 void InsetTabular::setLayoutForHiddenCells(DocumentClass const & dc)
7425 {
7426         for (Tabular::col_type c = 0; c < tabular.ncols(); ++c) {
7427                 for (Tabular::row_type r = 0; r < tabular.nrows(); ++r) {
7428                         if (!tabular.isPartOfMultiColumn(r,c) &&
7429                             !tabular.isPartOfMultiRow(r,c))
7430                                 continue;
7431
7432                         ParagraphList & parlist = tabular.cellInset(r,c)->paragraphs();
7433                         ParagraphList::iterator it = parlist.begin();
7434                         ParagraphList::iterator const en = parlist.end();
7435                         for (; it != en; ++it)
7436                                         it->setLayout(dc.plainLayout());
7437                 }
7438         }
7439 }
7440
7441
7442 } // namespace lyx