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