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