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