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