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