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