]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
44f251a72867df4bc6eed6325256a2b14cc4368b
[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         col_type const col = tabular.cellColumn(cell);
4237
4238         // Top
4239         bool drawline = tabular.topLine(cell)
4240                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
4241         bool heavy = tabular.use_booktabs && row == 0 && tabular.rowTopLine(row);
4242         tabline(pi, x, y, x + w, y, drawline, heavy);
4243
4244         // Bottom
4245         drawline = tabular.bottomLine(cell);
4246         row_type const lastrow = tabular.nrows() - 1;
4247         // Consider multi-rows
4248         row_type r = row;
4249         while (r < lastrow && tabular.isMultiRow(tabular.cellIndex(r, col))
4250                 && tabular.isPartOfMultiRow(r + 1, col))
4251                 r++;
4252         heavy = tabular.use_booktabs
4253                 && ((row == lastrow && tabular.rowBottomLine(row))
4254                     || (r == lastrow && tabular.rowBottomLine(r)));
4255         tabline(pi, x, y + h, x + w, y + h, drawline, heavy);
4256
4257         // Left
4258         drawline = tabular.leftLine(cell)
4259                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
4260         tabline(pi, x, y, x, y + h, drawline);
4261
4262         // Right
4263         x -= tabular.interColumnSpace(cell);
4264         col_type next_cell_col = col + 1;
4265         while (next_cell_col < tabular.ncols()
4266                 && tabular.isMultiColumn(tabular.cellIndex(row, next_cell_col)))
4267                 next_cell_col++;
4268         drawline = tabular.rightLine(cell)
4269                    || (next_cell_col < tabular.ncols()
4270                        && tabular.leftLine(tabular.cellIndex(row, next_cell_col)));
4271         tabline(pi, x + w, y, x + w, y + h, drawline);
4272 }
4273
4274
4275 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
4276 {
4277         //lyxerr << "InsetTabular::edit: " << this << endl;
4278         cur.finishUndo();
4279         cur.push(*this);
4280         if (front) {
4281                 if (isRightToLeft(cur))
4282                         cur.idx() = tabular.getLastCellInRow(0);
4283                 else
4284                         cur.idx() = 0;
4285                 cur.pit() = 0;
4286                 cur.pos() = 0;
4287         } else {
4288                 if (isRightToLeft(cur))
4289                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
4290                 else
4291                         cur.idx() = tabular.numberofcells - 1;
4292                 cur.pit() = 0;
4293                 cur.pos() = cur.lastpos(); // FIXME crude guess
4294         }
4295         cur.setCurrentFont();
4296         // FIXME: this accesses the position cache before it is initialized
4297         //cur.bv().fitCursor();
4298 }
4299
4300
4301 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
4302 {
4303         // In a longtable, tell captions what the current float is
4304         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
4305         string const saveflt = cnts.current_float();
4306         if (tabular.is_long_tabular) {
4307                 cnts.current_float("table");
4308                 // in longtables, we only step the counter once
4309                 cnts.step(from_ascii("table"), utype);
4310                 cnts.isLongtable(true);
4311         }
4312
4313         ParIterator it2 = it;
4314         it2.forwardPos();
4315         size_t const end = it2.nargs();
4316         for ( ; it2.idx() < end; it2.top().forwardIdx())
4317                 buffer().updateBuffer(it2, utype);
4318
4319         //reset afterwards
4320         if (tabular.is_long_tabular) {
4321                 cnts.current_float(saveflt);
4322                 cnts.isLongtable(false);
4323         }
4324 }
4325
4326
4327 void InsetTabular::addToToc(DocIterator const & cpit, bool output_active,
4328                                                         UpdateType utype, TocBackend & backend) const
4329 {
4330         DocIterator dit = cpit;
4331         dit.forwardPos();
4332         size_t const end = dit.nargs();
4333         for ( ; dit.idx() < end; dit.top().forwardIdx())
4334                 cell(dit.idx())->addToToc(dit, output_active, utype, backend);
4335 }
4336
4337
4338 bool InsetTabular::hitSelectRow(BufferView const & bv, int x) const
4339 {
4340         int const x0 = xo(bv) + ADD_TO_TABULAR_WIDTH;
4341         return x < x0 || x > x0 + tabular.width();
4342 }
4343
4344
4345 bool InsetTabular::hitSelectColumn(BufferView const & bv, int y) const
4346 {
4347         int const y0 = yo(bv) - tabular.rowAscent(0) + tabular.offsetVAlignment();
4348         // FIXME: using ADD_TO_TABULAR_WIDTH is not really correct since
4349         // there is no margin added vertically to tabular insets.
4350         // However, it works for now.
4351         return y < y0 + ADD_TO_TABULAR_WIDTH || y > y0 + tabular.height() - ADD_TO_TABULAR_WIDTH;
4352 }
4353
4354
4355 bool InsetTabular::clickable(BufferView const & bv, int x, int y) const
4356 {
4357         return hitSelectRow(bv, x) || hitSelectColumn(bv, y);
4358 }
4359
4360
4361 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
4362 {
4363         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
4364                              << "\n  cur:" << cur);
4365         CursorSlice sl = cur.top();
4366         Cursor & bvcur = cur.bv().cursor();
4367
4368         FuncCode const act = cmd.action();
4369
4370         switch (act) {
4371
4372         case LFUN_MOUSE_PRESS: {
4373                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
4374                 // select row
4375                 if (hitSelectRow(cur.bv(), cmd.x())) {
4376                         row_type r = rowFromY(cur, cmd.y());
4377                         cur.idx() = tabular.getFirstCellInRow(r);
4378                         cur.pit() = 0;
4379                         cur.pos() = 0;
4380                         cur.resetAnchor();
4381                         cur.idx() = tabular.getLastCellInRow(r);
4382                         cur.pit() = cur.lastpit();
4383                         cur.pos() = cur.lastpos();
4384                         cur.selection(true);
4385                         bvcur = cur;
4386                         rowselect_ = true;
4387                         break;
4388                 }
4389                 // select column
4390                 if (hitSelectColumn(cur.bv(), cmd.y())) {
4391                         col_type c = columnFromX(cur, cmd.x());
4392                         cur.idx() = tabular.cellIndex(0, c);
4393                         cur.pit() = 0;
4394                         cur.pos() = 0;
4395                         cur.resetAnchor();
4396                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
4397                         cur.pit() = cur.lastpit();
4398                         cur.pos() = cur.lastpos();
4399                         cur.selection(true);
4400                         bvcur = cur;
4401                         colselect_ = true;
4402                         break;
4403                 }
4404                 // do not reset cursor/selection if we have selected
4405                 // some cells (bug 2715).
4406                 if (cmd.button() == mouse_button::button3
4407                     && &bvcur.selBegin().inset() == this
4408                     && bvcur.selIsMultiCell())
4409                         ;
4410                 else
4411                         // Let InsetTableCell do it
4412                         cell(cur.idx())->dispatch(cur, cmd);
4413                 break;
4414         }
4415         case LFUN_MOUSE_MOTION:
4416                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
4417                 if (cmd.button() == mouse_button::button1) {
4418                         // only accept motions to places not deeper nested than the real anchor
4419                         if (!bvcur.realAnchor().hasPart(cur)) {
4420                                 cur.undispatched();
4421                                 break;
4422                         }
4423                         // select (additional) row
4424                         if (rowselect_) {
4425                                 row_type r = rowFromY(cur, cmd.y());
4426                                 cur.idx() = tabular.getLastCellInRow(r);
4427                                 // we need to reset the cursor's pit and pos now, as the old ones
4428                                 // may no longer be valid.
4429                                 cur.pit() = 0;
4430                                 cur.pos() = 0;
4431                                 bvcur.setCursor(cur);
4432                                 bvcur.selection(true);
4433                                 break;
4434                         }
4435                         // select (additional) column
4436                         if (colselect_) {
4437                                 col_type c = columnFromX(cur, cmd.x());
4438                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
4439                                 // we need to reset the cursor's pit and pos now, as the old ones
4440                                 // may no longer be valid.
4441                                 cur.pit() = 0;
4442                                 cur.pos() = 0;
4443                                 bvcur.setCursor(cur);
4444                                 bvcur.selection(true);
4445                                 break;
4446                         }
4447                         // only update if selection changes
4448                         if (bvcur.idx() == cur.idx() &&
4449                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
4450                                 cur.noScreenUpdate();
4451                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
4452                         bvcur.setCursor(cur);
4453                         bvcur.selection(true);
4454                         // if this is a multicell selection, we just set the cursor to
4455                         // the beginning of the cell's text.
4456                         if (bvcur.selIsMultiCell()) {
4457                                 bvcur.pit() = bvcur.lastpit();
4458                                 bvcur.pos() = bvcur.lastpos();
4459                         }
4460                 }
4461                 break;
4462
4463         case LFUN_MOUSE_RELEASE:
4464                 rowselect_ = false;
4465                 colselect_ = false;
4466                 break;
4467
4468         case LFUN_CELL_BACKWARD:
4469                 movePrevCell(cur);
4470                 cur.selection(false);
4471                 break;
4472
4473         case LFUN_CELL_FORWARD:
4474                 moveNextCell(cur);
4475                 cur.selection(false);
4476                 break;
4477
4478         case LFUN_CHAR_FORWARD_SELECT:
4479         case LFUN_CHAR_FORWARD:
4480         case LFUN_CHAR_BACKWARD_SELECT:
4481         case LFUN_CHAR_BACKWARD:
4482         case LFUN_CHAR_RIGHT_SELECT:
4483         case LFUN_CHAR_RIGHT:
4484         case LFUN_CHAR_LEFT_SELECT:
4485         case LFUN_CHAR_LEFT:
4486         case LFUN_WORD_FORWARD:
4487         case LFUN_WORD_FORWARD_SELECT:
4488         case LFUN_WORD_BACKWARD:
4489         case LFUN_WORD_BACKWARD_SELECT:
4490         case LFUN_WORD_RIGHT:
4491         case LFUN_WORD_RIGHT_SELECT:
4492         case LFUN_WORD_LEFT:
4493         case LFUN_WORD_LEFT_SELECT: {
4494                 // determine whether we move to next or previous cell, where to enter
4495                 // the new cell from, and which command to "finish" (i.e., exit the
4496                 // inset) with:
4497                 bool next_cell;
4498                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
4499                 FuncCode finish_lfun;
4500
4501                 if (act == LFUN_CHAR_FORWARD
4502                                 || act == LFUN_CHAR_FORWARD_SELECT
4503                                 || act == LFUN_WORD_FORWARD
4504                                 || act == LFUN_WORD_FORWARD_SELECT) {
4505                         next_cell = true;
4506                         finish_lfun = LFUN_FINISHED_FORWARD;
4507                 }
4508                 else if (act == LFUN_CHAR_BACKWARD
4509                                 || act == LFUN_CHAR_BACKWARD_SELECT
4510                                 || act == LFUN_WORD_BACKWARD
4511                                 || act == LFUN_WORD_BACKWARD_SELECT) {
4512                         next_cell = false;
4513                         finish_lfun = LFUN_FINISHED_BACKWARD;
4514                 }
4515                 // LEFT or RIGHT commands --- the interpretation will depend on the
4516                 // table's direction.
4517                 else {
4518                         bool const right = act == LFUN_CHAR_RIGHT
4519                                 || act == LFUN_CHAR_RIGHT_SELECT
4520                                 || act == LFUN_WORD_RIGHT
4521                                 || act == LFUN_WORD_RIGHT_SELECT;
4522                         next_cell = isRightToLeft(cur) != right;
4523
4524                         if (lyxrc.visual_cursor)
4525                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
4526
4527                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
4528                 }
4529
4530                 bool const select =     act == LFUN_CHAR_FORWARD_SELECT
4531                     || act == LFUN_CHAR_BACKWARD_SELECT
4532                     || act == LFUN_CHAR_RIGHT_SELECT
4533                     || act == LFUN_CHAR_LEFT_SELECT
4534                         || act == LFUN_WORD_FORWARD_SELECT
4535                         || act == LFUN_WORD_RIGHT_SELECT
4536                         || act == LFUN_WORD_BACKWARD_SELECT
4537                         || act == LFUN_WORD_LEFT_SELECT;
4538
4539                 // If we have a multicell selection or we're
4540                 // not doing some LFUN_*_SELECT thing anyway...
4541                 if (!cur.selIsMultiCell() || !select) {
4542                         col_type const c = tabular.cellColumn(cur.idx());
4543                         row_type const r = tabular.cellRow(cur.idx());
4544                         // Are we trying to select the whole cell and is the whole cell
4545                         // not yet selected?
4546                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
4547                                 ((next_cell && cur.pit() == cur.lastpit()
4548                                 && cur.pos() == cur.lastpos())
4549                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
4550
4551                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
4552
4553                         // ...try to dispatch to the cell's inset.
4554                         cell(cur.idx())->dispatch(cur, cmd);
4555
4556                         // When we already have a selection we want to select the whole cell
4557                         // before going to the next cell.
4558                         if (select_whole && !empty_cell){
4559                                 getText(cur.idx())->selectAll(cur);
4560                                 cur.dispatched();
4561                                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4562                                 break;
4563                         }
4564
4565                         // FIXME: When we support the selection of an empty cell, remove
4566                         // the !empty_cell from this condition. For now we jump to the next
4567                         // cell if the current cell is empty.
4568                         if (cur.result().dispatched() && !empty_cell)
4569                                 break;
4570                 }
4571
4572                 // move to next/prev cell, as appropriate
4573                 // note that we will always do this if we're selecting and we have
4574                 // a multicell selection
4575                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
4576                         << " cell from: " << int(entry_from));
4577                 if (next_cell)
4578                         moveNextCell(cur, entry_from);
4579                 else
4580                         movePrevCell(cur, entry_from);
4581                 // if we're exiting the table, call the appropriate FINISHED lfun
4582                 if (sl == cur.top()) {
4583                         cmd = FuncRequest(finish_lfun);
4584                         cur.undispatched();
4585                 } else
4586                         cur.dispatched();
4587
4588                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4589                 break;
4590
4591         }
4592
4593         case LFUN_DOWN_SELECT:
4594         case LFUN_DOWN:
4595                 if (!(cur.selection() && cur.selIsMultiCell()))
4596                         cell(cur.idx())->dispatch(cur, cmd);
4597
4598                 cur.dispatched(); // override the cell's decision
4599                 if (sl == cur.top()) {
4600                         // if our Text didn't do anything to the cursor
4601                         // then we try to put the cursor into the cell below
4602                         // setting also the right targetX.
4603                         cur.selHandle(act == LFUN_DOWN_SELECT);
4604                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
4605                                 int const xtarget = cur.targetX();
4606                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4607                                 // an inconsistent state until pos() has been set. Be careful
4608                                 // what you do with it!
4609                                 cur.idx() = tabular.cellBelow(cur.idx());
4610                                 cur.pit() = 0;
4611                                 TextMetrics const & tm =
4612                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
4613                                 cur.pos() = tm.x2pos(cur.pit(), 0, xtarget);
4614                                 cur.setCurrentFont();
4615                         }
4616                 }
4617                 if (sl == cur.top()) {
4618                         // we trick it to go to forward after leaving the
4619                         // tabular.
4620                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
4621                         cur.undispatched();
4622                 }
4623                 if (cur.selIsMultiCell()) {
4624                         cur.pit() = cur.lastpit();
4625                         cur.pos() = cur.lastpos();
4626                         cur.setCurrentFont();
4627                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4628                         return;
4629                 }
4630                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4631                 break;
4632
4633         case LFUN_UP_SELECT:
4634         case LFUN_UP:
4635                 if (!(cur.selection() && cur.selIsMultiCell()))
4636                         cell(cur.idx())->dispatch(cur, cmd);
4637                 cur.dispatched(); // override the cell's decision
4638                 if (sl == cur.top()) {
4639                         // if our Text didn't do anything to the cursor
4640                         // then we try to put the cursor into the cell above
4641                         // setting also the right targetX.
4642                         cur.selHandle(act == LFUN_UP_SELECT);
4643                         if (tabular.cellRow(cur.idx()) != 0) {
4644                                 int const xtarget = cur.targetX();
4645                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4646                                 // an inconsistent state until pos() has been set. Be careful
4647                                 // what you do with it!
4648                                 cur.idx() = tabular.cellAbove(cur.idx());
4649                                 cur.pit() = cur.lastpit();
4650                                 Text const * text = cell(cur.idx())->getText(0);
4651                                 TextMetrics const & tm = cur.bv().textMetrics(text);
4652                                 ParagraphMetrics const & pm =
4653                                         tm.parMetrics(cur.lastpit());
4654                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, xtarget);
4655                                 cur.setCurrentFont();
4656                         }
4657                 }
4658                 if (sl == cur.top()) {
4659                         cmd = FuncRequest(LFUN_UP);
4660                         cur.undispatched();
4661                 }
4662                 if (cur.selIsMultiCell()) {
4663                         cur.pit() = 0;
4664                         cur.pos() = cur.lastpos();
4665                         cur.setCurrentFont();
4666                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4667                         return;
4668                 }
4669                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4670                 break;
4671
4672         case LFUN_LAYOUT_TABULAR:
4673                 cur.bv().showDialog("tabular");
4674                 break;
4675
4676         case LFUN_INSET_MODIFY:
4677                 // we come from the dialog
4678                 if (cmd.getArg(0) == "tabular")
4679                         tabularFeatures(cur, cmd.getLongArg(1));
4680                 else
4681                         cur.undispatched();
4682                 break;
4683
4684         case LFUN_TABULAR_FEATURE:
4685                 tabularFeatures(cur, to_utf8(cmd.argument()));
4686                 break;
4687
4688         // insert file functions
4689         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
4690         case LFUN_FILE_INSERT_PLAINTEXT:
4691                 // FIXME UNICODE
4692                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
4693                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
4694                                 FileName(to_utf8(cmd.argument())));
4695                         if (tmpstr.empty())
4696                                 break;
4697                         cur.recordUndoInset();
4698                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
4699                                 // content has been replaced,
4700                                 // so cursor might be invalid
4701                                 cur.pos() = cur.lastpos();
4702                                 cur.pit() = cur.lastpit();
4703                                 bvcur.setCursor(cur);
4704                         } else
4705                                 cur.undispatched();
4706                 }
4707                 break;
4708
4709         case LFUN_CUT:
4710                 if (cur.selIsMultiCell()) {
4711                         if (copySelection(cur)) {
4712                                 cur.recordUndoInset();
4713                                 cutSelection(cur);
4714                         }
4715                 } else
4716                         cell(cur.idx())->dispatch(cur, cmd);
4717                 break;
4718
4719         case LFUN_SELF_INSERT:
4720                 if (cur.selIsMultiCell()) {
4721                         cur.recordUndoInset();
4722                         cutSelection(cur);
4723                         BufferView * bv = &cur.bv();
4724                         docstring::const_iterator cit = cmd.argument().begin();
4725                         docstring::const_iterator const end = cmd.argument().end();
4726                         for (; cit != end; ++cit)
4727                                 bv->translateAndInsert(*cit, getText(cur.idx()), cur);
4728
4729                         cur.resetAnchor();
4730                         bv->bookmarkEditPosition();
4731                 } else
4732                         cell(cur.idx())->dispatch(cur, cmd);
4733                 break;
4734
4735         case LFUN_CHAR_DELETE_BACKWARD:
4736         case LFUN_CHAR_DELETE_FORWARD:
4737                 if (cur.selIsMultiCell()) {
4738                         cur.recordUndoInset();
4739                         cutSelection(cur);
4740                 } else
4741                         cell(cur.idx())->dispatch(cur, cmd);
4742                 break;
4743
4744         case LFUN_COPY:
4745                 if (!cur.selection())
4746                         break;
4747                 if (cur.selIsMultiCell()) {
4748                         cur.finishUndo();
4749                         copySelection(cur);
4750                 } else
4751                         cell(cur.idx())->dispatch(cur, cmd);
4752                 break;
4753
4754         case LFUN_CLIPBOARD_PASTE:
4755         case LFUN_PRIMARY_SELECTION_PASTE: {
4756                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
4757                         theClipboard().getAsText(Clipboard::PlainTextType) :
4758                         theSelection().get();
4759                 if (clip.empty())
4760                         break;
4761                 // pass to InsertPlaintextString, but
4762                 // only if we have multi-cell content
4763                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
4764                         cur.recordUndoInset();
4765                         if (insertPlaintextString(cur.bv(), clip, false)) {
4766                                 // content has been replaced,
4767                                 // so cursor might be invalid
4768                                 cur.pos() = cur.lastpos();
4769                                 cur.pit() = cur.lastpit();
4770                                 bvcur.setCursor(cur);
4771                                 break;
4772                         }
4773                 }
4774                 // Let the cell handle normal text
4775                 cell(cur.idx())->dispatch(cur, cmd);
4776                 break;
4777         }
4778
4779         case LFUN_PASTE:
4780                 if (!tabularStackDirty()) {
4781                         if (!cur.selIsMultiCell())
4782                                 cell(cur.idx())->dispatch(cur, cmd);
4783                         break;
4784                 }
4785                 if (theClipboard().isInternal()) {
4786                         cur.recordUndoInset();
4787                         pasteClipboard(cur);
4788                 }
4789                 break;
4790
4791         case LFUN_FONT_EMPH:
4792         case LFUN_FONT_BOLD:
4793         case LFUN_FONT_BOLDSYMBOL:
4794         case LFUN_FONT_ROMAN:
4795         case LFUN_FONT_NOUN:
4796         case LFUN_FONT_ITAL:
4797         case LFUN_FONT_FRAK:
4798         case LFUN_FONT_TYPEWRITER:
4799         case LFUN_FONT_SANS:
4800         case LFUN_TEXTSTYLE_APPLY:
4801         case LFUN_TEXTSTYLE_UPDATE:
4802         case LFUN_FONT_SIZE:
4803         case LFUN_FONT_UNDERLINE:
4804         case LFUN_FONT_STRIKEOUT:
4805         case LFUN_FONT_CROSSOUT:
4806         case LFUN_FONT_UNDERUNDERLINE:
4807         case LFUN_FONT_UNDERWAVE:
4808         case LFUN_LANGUAGE:
4809         case LFUN_PARAGRAPH_PARAMS_APPLY:
4810         case LFUN_PARAGRAPH_PARAMS:
4811         case LFUN_WORD_CAPITALIZE:
4812         case LFUN_WORD_UPCASE:
4813         case LFUN_WORD_LOWCASE:
4814         case LFUN_CHARS_TRANSPOSE:
4815                 if (cur.selIsMultiCell()) {
4816                         row_type rs, re;
4817                         col_type cs, ce;
4818                         getSelection(cur, rs, re, cs, ce);
4819                         Cursor tmpcur = cur;
4820                         for (row_type r = rs; r <= re; ++r) {
4821                                 for (col_type c = cs; c <= ce; ++c) {
4822                                         // cursor follows cell:
4823                                         tmpcur.idx() = tabular.cellIndex(r, c);
4824                                         // select this cell only:
4825                                         tmpcur.pit() = 0;
4826                                         tmpcur.pos() = 0;
4827                                         tmpcur.resetAnchor();
4828                                         tmpcur.pit() = tmpcur.lastpit();
4829                                         tmpcur.pos() = tmpcur.top().lastpos();
4830                                         tmpcur.setCursor(tmpcur);
4831                                         tmpcur.setSelection();
4832                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
4833                                 }
4834                         }
4835                         break;
4836                 } else {
4837                         cell(cur.idx())->dispatch(cur, cmd);
4838                         break;
4839                 }
4840
4841         case LFUN_INSET_SETTINGS:
4842                 // relay this lfun to Inset, not to the cell.
4843                 Inset::doDispatch(cur, cmd);
4844                 break;
4845
4846         default:
4847                 // we try to handle this event in the insets dispatch function.
4848                 cell(cur.idx())->dispatch(cur, cmd);
4849                 break;
4850         }
4851 }
4852
4853
4854 bool InsetTabular::getFeatureStatus(Cursor & cur, string const & s,
4855                       string const & argument, FuncStatus & status) const
4856 {
4857
4858                 int action = Tabular::LAST_ACTION;
4859                 int i = 0;
4860                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4861                         if (tabularFeature[i].feature == s) {
4862                                 action = tabularFeature[i].action;
4863                                 break;
4864                         }
4865                 }
4866                 if (action == Tabular::LAST_ACTION) {
4867                         status.clear();
4868                         status.setUnknown(true);
4869                         return true;
4870                 }
4871
4872                 row_type sel_row_start = 0;
4873                 row_type sel_row_end = 0;
4874                 col_type sel_col_start = 0;
4875                 col_type sel_col_end = 0;
4876                 Tabular::ltType dummyltt;
4877                 bool flag = true;
4878
4879                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4880
4881                 switch (action) {
4882                 case Tabular::SET_PWIDTH:
4883                 case Tabular::SET_MPWIDTH:
4884                 case Tabular::TOGGLE_VARWIDTH_COLUMN:
4885                 case Tabular::SET_SPECIAL_COLUMN:
4886                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4887                 case Tabular::APPEND_ROW:
4888                 case Tabular::APPEND_COLUMN:
4889                 case Tabular::DELETE_ROW:
4890                 case Tabular::DELETE_COLUMN:
4891                 case Tabular::COPY_ROW:
4892                 case Tabular::COPY_COLUMN:
4893                 case Tabular::SET_TOP_SPACE:
4894                 case Tabular::SET_BOTTOM_SPACE:
4895                 case Tabular::SET_INTERLINE_SPACE:
4896                         status.clear();
4897                         return true;
4898
4899                 case Tabular::SET_TABULAR_WIDTH:
4900                         status.setEnabled(!tabular.rotate
4901                                 && tabular.tabular_valignment == Tabular::LYX_VALIGN_MIDDLE);
4902                         break;
4903
4904                 case Tabular::MOVE_COLUMN_RIGHT:
4905                 case Tabular::MOVE_COLUMN_LEFT:
4906                 case Tabular::MOVE_ROW_DOWN:
4907                 case Tabular::MOVE_ROW_UP: {
4908                         if (cur.selection()) {
4909                                 status.message(_("Selections not supported."));
4910                                 status.setEnabled(false);
4911                                 break;
4912                         }
4913
4914                         if ((action == Tabular::MOVE_COLUMN_RIGHT &&
4915                                 tabular.ncols() == tabular.cellColumn(cur.idx()) + 1) ||
4916                             (action == Tabular::MOVE_COLUMN_LEFT &&
4917                                 tabular.cellColumn(cur.idx()) == 0) ||
4918                             (action == Tabular::MOVE_ROW_DOWN &&
4919                                 tabular.nrows() == tabular.cellRow(cur.idx()) + 1) ||
4920                             (action == Tabular::MOVE_ROW_UP &&
4921                                 tabular.cellRow(cur.idx()) == 0)) {
4922                                         status.setEnabled(false);
4923                                         break;
4924                         }
4925
4926                         if (action == Tabular::MOVE_COLUMN_RIGHT ||
4927                             action == Tabular::MOVE_COLUMN_LEFT) {
4928                                 if (tabular.hasMultiColumn(tabular.cellColumn(cur.idx())) ||
4929                                     tabular.hasMultiColumn(tabular.cellColumn(cur.idx()) +
4930                                         (action == Tabular::MOVE_COLUMN_RIGHT ? 1 : -1))) {
4931                                         status.message(_("Multi-column in current or"
4932                                                          " destination column."));
4933                                         status.setEnabled(false);
4934                                         break;
4935                                 }
4936                         }
4937
4938                         if (action == Tabular::MOVE_ROW_DOWN ||
4939                             action == Tabular::MOVE_ROW_UP) {
4940                                 if (tabular.hasMultiRow(tabular.cellRow(cur.idx())) ||
4941                                     tabular.hasMultiRow(tabular.cellRow(cur.idx()) +
4942                                         (action == Tabular::MOVE_ROW_DOWN ? 1 : -1))) {
4943                                         status.message(_("Multi-row in current or"
4944                                                          " destination row."));
4945                                         status.setEnabled(false);
4946                                         break;
4947                                 }
4948                         }
4949
4950                         status.setEnabled(true);
4951                         break;
4952                 }
4953
4954                 case Tabular::SET_DECIMAL_POINT:
4955                         status.setEnabled(
4956                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
4957                         break;
4958
4959                 case Tabular::SET_MULTICOLUMN:
4960                 case Tabular::UNSET_MULTICOLUMN:
4961                 case Tabular::MULTICOLUMN:
4962                         // If a row is set as longtable caption, it must not be allowed
4963                         // to unset that this row is a multicolumn.
4964                         status.setEnabled(sel_row_start == sel_row_end
4965                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4966                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4967                         break;
4968
4969                 case Tabular::SET_MULTIROW:
4970                 case Tabular::UNSET_MULTIROW:
4971                 case Tabular::MULTIROW:
4972                         // If a row is set as longtable caption, it must not be allowed
4973                         // to unset that this row is a multirow.
4974                         status.setEnabled(sel_col_start == sel_col_end
4975                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4976                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4977                         break;
4978
4979                 case Tabular::SET_ALL_LINES:
4980                 case Tabular::UNSET_ALL_LINES:
4981                 case Tabular::SET_INNER_LINES:
4982                 case Tabular::SET_BORDER_LINES:
4983                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4984                         break;
4985
4986                 case Tabular::SET_LINE_TOP:
4987                 case Tabular::SET_LINE_BOTTOM:
4988                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4989                         break;
4990
4991                 case Tabular::SET_LINE_LEFT:
4992                 case Tabular::SET_LINE_RIGHT:
4993                         status.setEnabled(!tabular.use_booktabs
4994                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4995                         break;
4996
4997                 case Tabular::TOGGLE_LINE_TOP:
4998                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4999                         status.setOnOff(tabular.topLine(cur.idx()));
5000                         break;
5001
5002                 case Tabular::TOGGLE_LINE_BOTTOM:
5003                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
5004                         status.setOnOff(tabular.bottomLine(cur.idx()));
5005                         break;
5006
5007                 case Tabular::TOGGLE_LINE_LEFT:
5008                         status.setEnabled(!tabular.use_booktabs
5009                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5010                         status.setOnOff(tabular.leftLine(cur.idx()));
5011                         break;
5012
5013                 case Tabular::TOGGLE_LINE_RIGHT:
5014                         status.setEnabled(!tabular.use_booktabs
5015                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
5016                         status.setOnOff(tabular.rightLine(cur.idx()));
5017                         break;
5018
5019                 // multirow cells only inherit the alignment of the column if the column has
5020                 // no width, otherwise they are left-aligned
5021                 // therefore allow always left but right and center only if there is no width
5022                 case Tabular::M_ALIGN_LEFT:
5023                         flag = false;
5024                         // fall through
5025                 case Tabular::ALIGN_LEFT:
5026                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
5027                         break;
5028
5029                 case Tabular::M_ALIGN_RIGHT:
5030                         flag = false;
5031                         // fall through
5032                 case Tabular::ALIGN_RIGHT:
5033                         status.setEnabled(!(tabular.isMultiRow(cur.idx())
5034                                 && !tabular.getPWidth(cur.idx()).zero()));
5035                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
5036                         break;
5037
5038                 case Tabular::M_ALIGN_CENTER:
5039                         flag = false;
5040                         // fall through
5041                 case Tabular::ALIGN_CENTER:
5042                         status.setEnabled(!(tabular.isMultiRow(cur.idx())
5043                                 && !tabular.getPWidth(cur.idx()).zero()));
5044                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
5045                         break;
5046
5047                 case Tabular::ALIGN_BLOCK:
5048                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
5049                                 && !tabular.isMultiRow(cur.idx()));
5050                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
5051                         break;
5052
5053                 case Tabular::ALIGN_DECIMAL:
5054                         status.setEnabled(!tabular.isMultiRow(cur.idx())
5055                                 && !tabular.isMultiColumn(cur.idx()));
5056                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
5057                         break;
5058
5059                 case Tabular::M_VALIGN_TOP:
5060                         flag = false;
5061                         // fall through
5062                 case Tabular::VALIGN_TOP:
5063                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
5064                                 && !tabular.isMultiRow(cur.idx()));
5065                         status.setOnOff(
5066                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
5067                         break;
5068
5069                 case Tabular::M_VALIGN_BOTTOM:
5070                         flag = false;
5071                         // fall through
5072                 case Tabular::VALIGN_BOTTOM:
5073                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
5074                                 && !tabular.isMultiRow(cur.idx()));
5075                         status.setOnOff(
5076                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
5077                         break;
5078
5079                 case Tabular::M_VALIGN_MIDDLE:
5080                         flag = false;
5081                         // fall through
5082                 case Tabular::VALIGN_MIDDLE:
5083                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
5084                                 && !tabular.isMultiRow(cur.idx()));
5085                         status.setOnOff(
5086                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
5087                         break;
5088
5089                 case Tabular::SET_LONGTABULAR:
5090                 case Tabular::TOGGLE_LONGTABULAR:
5091                         // setting as longtable is not allowed when table is inside a float
5092                         if (cur.innerInsetOfType(FLOAT_CODE) != 0
5093                                 || cur.innerInsetOfType(WRAP_CODE) != 0)
5094                                 status.setEnabled(false);
5095                         else
5096                                 status.setEnabled(true);
5097                         status.setOnOff(tabular.is_long_tabular);
5098                         break;
5099
5100                 case Tabular::UNSET_LONGTABULAR:
5101                         status.setOnOff(!tabular.is_long_tabular);
5102                         break;
5103
5104                 case Tabular::TOGGLE_ROTATE_TABULAR:
5105                 case Tabular::SET_ROTATE_TABULAR:
5106                         status.setOnOff(tabular.rotate != 0);
5107                         break;
5108
5109                 case Tabular::TABULAR_VALIGN_TOP:
5110                         status.setEnabled(tabular.tabular_width.zero());
5111                         status.setOnOff(tabular.tabular_valignment
5112                                 == Tabular::LYX_VALIGN_TOP);
5113                         break;
5114                 case Tabular::TABULAR_VALIGN_MIDDLE:
5115                         status.setEnabled(tabular.tabular_width.zero());
5116                         status.setOnOff(tabular.tabular_valignment
5117                                 == Tabular::LYX_VALIGN_MIDDLE);
5118                         break;
5119                 case Tabular::TABULAR_VALIGN_BOTTOM:
5120                         status.setEnabled(tabular.tabular_width.zero());
5121                         status.setOnOff(tabular.tabular_valignment
5122                                 == Tabular::LYX_VALIGN_BOTTOM);
5123                         break;
5124
5125                 case Tabular::LONGTABULAR_ALIGN_LEFT:
5126                         status.setOnOff(tabular.longtabular_alignment
5127                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
5128                         break;
5129                 case Tabular::LONGTABULAR_ALIGN_CENTER:
5130                         status.setOnOff(tabular.longtabular_alignment
5131                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
5132                         break;
5133                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
5134                         status.setOnOff(tabular.longtabular_alignment
5135                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
5136                         break;
5137
5138                 case Tabular::UNSET_ROTATE_TABULAR:
5139                         status.setOnOff(tabular.rotate == 0);
5140                         break;
5141
5142                 case Tabular::TOGGLE_ROTATE_CELL:
5143                 case Tabular::SET_ROTATE_CELL:
5144                         status.setOnOff(!oneCellHasRotationState(false,
5145                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
5146                         break;
5147
5148                 case Tabular::UNSET_ROTATE_CELL:
5149                         status.setOnOff(!oneCellHasRotationState(true,
5150                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
5151                         break;
5152
5153                 case Tabular::SET_USEBOX:
5154                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
5155                         break;
5156
5157                 // every row can only be one thing:
5158                 // either a footer or header
5159                 case Tabular::SET_LTFIRSTHEAD:
5160                         status.setEnabled(sel_row_start == sel_row_end);
5161                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
5162                         break;
5163
5164                 case Tabular::UNSET_LTFIRSTHEAD:
5165                         status.setEnabled(sel_row_start == sel_row_end);
5166                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
5167                         break;
5168
5169                 case Tabular::SET_LTHEAD:
5170                         status.setEnabled(sel_row_start == sel_row_end);
5171                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
5172                         break;
5173
5174                 case Tabular::UNSET_LTHEAD:
5175                         status.setEnabled(sel_row_start == sel_row_end);
5176                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
5177                         break;
5178
5179                 case Tabular::SET_LTFOOT:
5180                         status.setEnabled(sel_row_start == sel_row_end);
5181                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
5182                         break;
5183
5184                 case Tabular::UNSET_LTFOOT:
5185                         status.setEnabled(sel_row_start == sel_row_end);
5186                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
5187                         break;
5188
5189                 case Tabular::SET_LTLASTFOOT:
5190                         status.setEnabled(sel_row_start == sel_row_end);
5191                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
5192                         break;
5193
5194                 case Tabular::UNSET_LTLASTFOOT:
5195                         status.setEnabled(sel_row_start == sel_row_end);
5196                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
5197                         break;
5198
5199                 case Tabular::SET_LTNEWPAGE:
5200                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
5201                         break;
5202                 case Tabular::UNSET_LTNEWPAGE:
5203                         status.setOnOff(!tabular.getLTNewPage(sel_row_start));
5204                         break;
5205
5206                 // only one row in head/firsthead/foot/lasthead can be the caption
5207                 // and a multirow cannot be set as caption
5208                 case Tabular::SET_LTCAPTION:
5209                         status.setEnabled(sel_row_start == sel_row_end
5210                                 && (!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
5211                                  || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
5212                                 && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
5213                                  || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
5214                                 && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
5215                                  || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
5216                                 && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
5217                                  || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT))
5218                                 && !tabular.isMultiRow(sel_row_start));
5219                         status.setOnOff(tabular.ltCaption(sel_row_start));
5220                         break;
5221
5222                 case Tabular::UNSET_LTCAPTION:
5223                         status.setEnabled(sel_row_start == sel_row_end && tabular.ltCaption(sel_row_start));
5224                         break;
5225
5226                 case Tabular::TOGGLE_LTCAPTION:
5227                         status.setEnabled(sel_row_start == sel_row_end && (tabular.ltCaption(sel_row_start)
5228                                 || ((!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
5229                                   || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
5230                                  && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
5231                                   || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
5232                                  && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
5233                                   || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
5234                                  && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
5235                                   || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT)))));
5236                         status.setOnOff(tabular.ltCaption(sel_row_start));
5237                         break;
5238
5239                 case Tabular::TOGGLE_BOOKTABS:
5240                 case Tabular::SET_BOOKTABS:
5241                         status.setOnOff(tabular.use_booktabs);
5242                         break;
5243
5244                 case Tabular::UNSET_BOOKTABS:
5245                         status.setOnOff(!tabular.use_booktabs);
5246                         break;
5247
5248                 default:
5249                         status.clear();
5250                         status.setEnabled(false);
5251                         break;
5252                 }
5253                 return true;
5254 }
5255
5256
5257 // function sets an object as defined in FuncStatus.h:
5258 // states OK, Unknown, Disabled, On, Off.
5259 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
5260                              FuncStatus & status) const
5261 {
5262         switch (cmd.action()) {
5263         case LFUN_INSET_MODIFY:
5264                 if (cmd.getArg(0) != "tabular")
5265                         break;
5266                 if (cmd.getArg(1) == "for-dialog") {
5267                         // The dialog is asking the status of a command
5268                         if (&cur.inset() != this)
5269                                 break;
5270                         string action = cmd.getArg(2);
5271                         string arg = cmd.getLongArg(3);
5272                         return getFeatureStatus(cur, action, arg, status);
5273                 } else {
5274                         // We always enable the lfun if it is coming from the dialog
5275                         // because the dialog makes sure all the settings are valid,
5276                         // even though the first argument might not be valid now.
5277                         status.setEnabled(true);
5278                         return true;
5279                 }
5280
5281         case LFUN_TABULAR_FEATURE: {
5282                 if (&cur.inset() != this)
5283                         break;
5284                 string action = cmd.getArg(0);
5285                 string arg = cmd.getLongArg(1);
5286                 return getFeatureStatus(cur, action, arg, status);
5287         }
5288
5289         case LFUN_CAPTION_INSERT: {
5290                 // caption is only allowed in caption cell of longtable
5291                 if (!tabular.ltCaption(tabular.cellRow(cur.idx()))) {
5292                         status.setEnabled(false);
5293                         return true;
5294                 }
5295                 // only standard caption is allowed
5296                 string arg = cmd.getArg(0);
5297                 if (!arg.empty() && arg != "Standard") {
5298                         status.setEnabled(false);
5299                         return true;
5300                 }
5301                 // check if there is already a caption
5302                 bool have_caption = false;
5303                 InsetTableCell itc = InsetTableCell(*tabular.cellInset(cur.idx()));
5304                 ParagraphList::const_iterator pit = itc.paragraphs().begin();
5305                 ParagraphList::const_iterator pend = itc.paragraphs().end();
5306                 for (; pit != pend; ++pit) {
5307                         InsetList::const_iterator it  = pit->insetList().begin();
5308                         InsetList::const_iterator end = pit->insetList().end();
5309                         for (; it != end; ++it) {
5310                                 if (it->inset->lyxCode() == CAPTION_CODE) {
5311                                         have_caption = true;
5312                                         break;
5313                                 }
5314                         }
5315                 }
5316                 status.setEnabled(!have_caption);
5317                 return true;
5318         }
5319
5320         // These are only enabled inside tabular
5321         case LFUN_CELL_BACKWARD:
5322         case LFUN_CELL_FORWARD:
5323                 status.setEnabled(true);
5324                 return true;
5325
5326         // disable these with multiple cells selected
5327         case LFUN_INSET_INSERT:
5328         case LFUN_TABULAR_INSERT:
5329         case LFUN_FLEX_INSERT:
5330         case LFUN_FLOAT_INSERT:
5331         case LFUN_FLOAT_WIDE_INSERT:
5332         case LFUN_FOOTNOTE_INSERT:
5333         case LFUN_MARGINALNOTE_INSERT:
5334         case LFUN_MATH_INSERT:
5335         case LFUN_MATH_MODE:
5336         case LFUN_MATH_MUTATE:
5337         case LFUN_MATH_DISPLAY:
5338         case LFUN_NOTE_INSERT:
5339         case LFUN_ARGUMENT_INSERT:
5340         case LFUN_BOX_INSERT:
5341         case LFUN_BRANCH_INSERT:
5342         case LFUN_PHANTOM_INSERT:
5343         case LFUN_WRAP_INSERT:
5344         case LFUN_PREVIEW_INSERT:
5345         case LFUN_ERT_INSERT: {
5346                 if (cur.selIsMultiCell()) {
5347                         status.setEnabled(false);
5348                         return true;
5349                 } else
5350                         return cell(cur.idx())->getStatus(cur, cmd, status);
5351         }
5352
5353         // disable in non-fixed-width cells
5354         case LFUN_PARAGRAPH_BREAK:
5355                 // multirow does not allow paragraph breaks
5356                 if (tabular.isMultiRow(cur.idx())) {
5357                         status.setEnabled(false);
5358                         return true;
5359                 }
5360                 // fall through
5361         case LFUN_NEWLINE_INSERT:
5362                 if ((tabular.isMultiColumn(cur.idx()) || tabular.isMultiRow(cur.idx()))
5363                     && tabular.getPWidth(cur.idx()).zero()) {
5364                         status.setEnabled(false);
5365                         return true;
5366                 }
5367                 return cell(cur.idx())->getStatus(cur, cmd, status);
5368
5369         case LFUN_NEWPAGE_INSERT:
5370                 status.setEnabled(false);
5371                 return true;
5372
5373         case LFUN_PASTE:
5374                 if (tabularStackDirty() && theClipboard().isInternal()) {
5375                         if (cur.selIsMultiCell()) {
5376                                 row_type rs, re;
5377                                 col_type cs, ce;
5378                                 getSelection(cur, rs, re, cs, ce);
5379                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
5380                                           && paste_tabular->nrows() == re - rs + 1)
5381                                         status.setEnabled(true);
5382                                 else {
5383                                         status.setEnabled(false);
5384                                         status.message(_("Selection size should match clipboard content."));
5385                                 }
5386                         } else
5387                                 status.setEnabled(true);
5388                         return true;
5389                 }
5390                 return cell(cur.idx())->getStatus(cur, cmd, status);
5391
5392         case LFUN_INSET_SETTINGS:
5393                 // relay this lfun to Inset, not to the cell.
5394                 return Inset::getStatus(cur, cmd, status);
5395
5396         default:
5397                 // we try to handle this event in the insets dispatch function.
5398                 return cell(cur.idx())->getStatus(cur, cmd, status);
5399         }
5400         return false;
5401 }
5402
5403
5404 Inset::DisplayType InsetTabular::display() const
5405 {
5406                 if (tabular.is_long_tabular) {
5407                         switch (tabular.longtabular_alignment) {
5408                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
5409                                 return AlignLeft;
5410                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
5411                                 return AlignCenter;
5412                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
5413                                 return AlignRight;
5414                         default:
5415                                 return AlignCenter;
5416                         }
5417                 } else
5418                         return Inline;
5419 }
5420
5421
5422 void InsetTabular::latex(otexstream & os, OutputParams const & runparams) const
5423 {
5424         tabular.latex(os, runparams);
5425 }
5426
5427
5428 int InsetTabular::plaintext(odocstringstream & os,
5429         OutputParams const & runparams, size_t max_length) const
5430 {
5431         os << '\n'; // output table on a new line
5432         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
5433         tabular.plaintext(os, runparams, dp, false, 0, max_length);
5434         return PLAINTEXT_NEWLINE;
5435 }
5436
5437
5438 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
5439 {
5440         int ret = 0;
5441         Inset * master = 0;
5442
5443         // FIXME: Why not pass a proper DocIterator here?
5444 #if 0
5445         // if the table is inside a float it doesn't need the informaltable
5446         // wrapper. Search for it.
5447         for (master = owner(); master; master = master->owner())
5448                 if (master->lyxCode() == FLOAT_CODE)
5449                         break;
5450 #endif
5451
5452         if (!master) {
5453                 os << "<informaltable>";
5454                 ++ret;
5455         }
5456         ret += tabular.docbook(os, runparams);
5457         if (!master) {
5458                 os << "</informaltable>";
5459                 ++ret;
5460         }
5461         return ret;
5462 }
5463
5464
5465 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
5466 {
5467         return tabular.xhtml(xs, rp);
5468 }
5469
5470
5471 void InsetTabular::validate(LaTeXFeatures & features) const
5472 {
5473         tabular.validate(features);
5474         features.useInsetLayout(getLayout());
5475 }
5476
5477
5478 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
5479 {
5480         return tabular.cellInset(idx);
5481 }
5482
5483
5484 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
5485 {
5486         return tabular.cellInset(idx);
5487 }
5488
5489
5490 void InsetTabular::cursorPos(BufferView const & bv,
5491                 CursorSlice const & sl, bool boundary, int & x, int & y) const
5492 {
5493         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
5494
5495         // y offset     correction
5496         y += cellYPos(sl.idx());
5497         y += tabular.textVOffset(sl.idx());
5498         y += tabular.offsetVAlignment();
5499
5500         // x offset correction
5501         x += cellXPos(sl.idx());
5502         x += tabular.textHOffset(sl.idx());
5503         x += ADD_TO_TABULAR_WIDTH;
5504 }
5505
5506
5507 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
5508 {
5509         int xx = 0;
5510         int yy = 0;
5511         Inset const & inset = *tabular.cellInset(cell);
5512         Point o = bv.coordCache().getInsets().xy(&inset);
5513         int const xbeg = o.x_ - tabular.textHOffset(cell);
5514         int const xend = xbeg + tabular.cellWidth(cell);
5515         row_type const row = tabular.cellRow(cell);
5516         int const ybeg = o.y_ - tabular.rowAscent(row)
5517                 - tabular.interRowSpace(row) - tabular.textVOffset(cell);
5518         int const yend = ybeg + tabular.cellHeight(cell);
5519
5520         if (x < xbeg)
5521                 xx = xbeg - x;
5522         else if (x > xend)
5523                 xx = x - xend;
5524
5525         if (y < ybeg)
5526                 yy = ybeg - y;
5527         else if (y > yend)
5528                 yy = y - yend;
5529
5530         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
5531         //       << " ybeg=" << ybeg << " yend=" << yend
5532         //       << " xx=" << xx << " yy=" << yy
5533         //       << " dist=" << xx + yy << endl;
5534         return xx + yy;
5535 }
5536
5537
5538 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
5539 {
5540         //lyxerr << "InsetTabular::editXY: " << this << endl;
5541         cur.push(*this);
5542         cur.idx() = getNearestCell(cur.bv(), x, y);
5543         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
5544 }
5545
5546
5547 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
5548 {
5549         cur.idx() = getNearestCell(cur.bv(), x, y);
5550         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
5551 }
5552
5553
5554 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
5555 {
5556         idx_type idx_min = 0;
5557         int dist_min = numeric_limits<int>::max();
5558         for (idx_type i = 0, n = nargs(); i != n; ++i) {
5559                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
5560                         int const d = dist(bv, i, x, y);
5561                         if (d < dist_min) {
5562                                 dist_min = d;
5563                                 idx_min = i;
5564                         }
5565                 }
5566         }
5567         return idx_min;
5568 }
5569
5570
5571 int InsetTabular::cellYPos(idx_type const cell) const
5572 {
5573         row_type row = tabular.cellRow(cell);
5574         int ly = 0;
5575         for (row_type r = 0; r < row; ++r)
5576                 ly += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
5577                         + tabular.interRowSpace(r + 1);
5578         return ly;
5579 }
5580
5581
5582 int InsetTabular::cellXPos(idx_type const cell) const
5583 {
5584         col_type col = tabular.cellColumn(cell);
5585         int lx = 0;
5586         for (col_type c = 0; c < col; ++c)
5587                 lx += tabular.column_info[c].width;
5588         return lx;
5589 }
5590
5591
5592 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
5593 {
5594         row_type const row = tabular.cellRow(cur.idx());
5595         col_type const col = tabular.cellColumn(cur.idx());
5596
5597         if (isRightToLeft(cur)) {
5598                 if (tabular.cellColumn(cur.idx()) == 0) {
5599                         if (row == tabular.nrows() - 1)
5600                                 return;
5601                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
5602                 } else {
5603                         if (cur.idx() == 0)
5604                                 return;
5605                         if (col == 0)
5606                                 cur.idx() = tabular.getLastCellInRow(row - 1);
5607                         else
5608                                 cur.idx() = tabular.cellIndex(row, col - 1);
5609                 }
5610         } else {
5611                 if (tabular.isLastCell(cur.idx()))
5612                         return;
5613                 if (cur.idx() == tabular.getLastCellInRow(row))
5614                         cur.idx() = tabular.cellIndex(row + 1, 0);
5615                 else {
5616                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
5617                         cur.idx() = tabular.cellIndex(row, colnextcell);
5618                 }
5619         }
5620
5621         cur.boundary(false);
5622
5623         if (cur.selIsMultiCell()) {
5624                 cur.pit() = cur.lastpit();
5625                 cur.pos() = cur.lastpos();
5626                 return;
5627         }
5628
5629         cur.pit() = 0;
5630         cur.pos() = 0;
5631
5632         // in visual mode, place cursor at extreme left or right
5633
5634         switch(entry_from) {
5635
5636         case ENTRY_DIRECTION_RIGHT:
5637                 cur.posVisToRowExtremity(false /* !left */);
5638                 break;
5639         case ENTRY_DIRECTION_LEFT:
5640                 cur.posVisToRowExtremity(true /* left */);
5641                 break;
5642         case ENTRY_DIRECTION_IGNORE:
5643                 // nothing to do in this case
5644                 break;
5645
5646         }
5647         cur.setCurrentFont();
5648 }
5649
5650
5651 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
5652 {
5653         row_type const row = tabular.cellRow(cur.idx());
5654         col_type const col = tabular.cellColumn(cur.idx());
5655
5656         if (isRightToLeft(cur)) {
5657                 if (cur.idx() == tabular.getLastCellInRow(row)) {
5658                         if (row == 0)
5659                                 return;
5660                         cur.idx() = tabular.getFirstCellInRow(row);
5661                         cur.idx() = tabular.cellAbove(cur.idx());
5662                 } else {
5663                         if (tabular.isLastCell(cur.idx()))
5664                                 return;
5665                         if (cur.idx() == tabular.getLastCellInRow(row))
5666                                 cur.idx() = tabular.cellIndex(row + 1, 0);
5667                         else
5668                                 cur.idx() = tabular.cellIndex(row, col + 1);
5669                 }
5670         } else {
5671                 if (cur.idx() == 0) // first cell
5672                         return;
5673                 if (col == 0)
5674                         cur.idx() = tabular.getLastCellInRow(row - 1);
5675                 else
5676                         cur.idx() = tabular.cellIndex(row, col - 1);
5677         }
5678
5679         if (cur.selIsMultiCell()) {
5680                 cur.pit() = cur.lastpit();
5681                 cur.pos() = cur.lastpos();
5682                 return;
5683         }
5684
5685         cur.pit() = cur.lastpit();
5686         cur.pos() = cur.lastpos();
5687
5688         // in visual mode, place cursor at extreme left or right
5689
5690         switch(entry_from) {
5691
5692         case ENTRY_DIRECTION_RIGHT:
5693                 cur.posVisToRowExtremity(false /* !left */);
5694                 break;
5695         case ENTRY_DIRECTION_LEFT:
5696                 cur.posVisToRowExtremity(true /* left */);
5697                 break;
5698         case ENTRY_DIRECTION_IGNORE:
5699                 // nothing to do in this case
5700                 break;
5701
5702         }
5703         cur.setCurrentFont();
5704 }
5705
5706
5707 void InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
5708 {
5709         cur.recordUndoInset(this);
5710
5711         istringstream is(argument);
5712         // limit the size of strings we read to avoid memory problems
5713         is >> setw(65636);
5714         string s;
5715         // Safe guard.
5716         size_t safe_guard = 0;
5717         for (;;) {
5718                 if (is.eof())
5719                         return;
5720                 safe_guard++;
5721                 if (safe_guard > 1000) {
5722                         LYXERR0("parameter max count reached!");
5723                         return;
5724                 }
5725                 is >> s;
5726                 Tabular::Feature action = Tabular::LAST_ACTION;
5727
5728                 size_t i = 0;
5729                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
5730                         if (s != tabularFeature[i].feature)
5731                                 continue;
5732                         action = tabularFeature[i].action;
5733                         break;
5734                 }
5735                 if (action == Tabular::LAST_ACTION) {
5736                         LYXERR0("Feature not found " << s);
5737                         continue;
5738                 }
5739                 string val;
5740                 if (tabularFeature[i].need_value)
5741                         is >> val;
5742                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
5743                 tabularFeatures(cur, action, val);
5744         }
5745 }
5746
5747
5748 static void checkLongtableSpecial(Tabular::ltType & ltt,
5749                           string const & special, bool & flag)
5750 {
5751         if (special == "dl_above") {
5752                 ltt.topDL = flag;
5753                 ltt.set = false;
5754         } else if (special == "dl_below") {
5755                 ltt.bottomDL = flag;
5756                 ltt.set = false;
5757         } else if (special == "empty") {
5758                 ltt.empty = flag;
5759                 ltt.set = false;
5760         } else if (flag) {
5761                 ltt.empty = false;
5762                 ltt.set = true;
5763         }
5764 }
5765
5766
5767 bool InsetTabular::oneCellHasRotationState(bool rotated,
5768                 row_type row_start, row_type row_end,
5769                 col_type col_start, col_type col_end) const
5770 {
5771         for (row_type r = row_start; r <= row_end; ++r)
5772                 for (col_type c = col_start; c <= col_end; ++c)
5773                         if (rotated) {
5774                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) != 0)
5775                                         return true;
5776                         } else {
5777                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) == 0)
5778                                         return true;
5779                         }
5780         return false;
5781 }
5782
5783
5784 void InsetTabular::tabularFeatures(Cursor & cur,
5785         Tabular::Feature feature, string const & value)
5786 {
5787         col_type sel_col_start;
5788         col_type sel_col_end;
5789         row_type sel_row_start;
5790         row_type sel_row_end;
5791         bool setLines = false;
5792         bool setLinesInnerOnly = false;
5793         LyXAlignment setAlign = LYX_ALIGN_LEFT;
5794         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
5795
5796         switch (feature) {
5797
5798         case Tabular::M_ALIGN_LEFT:
5799         case Tabular::ALIGN_LEFT:
5800                 setAlign = LYX_ALIGN_LEFT;
5801                 break;
5802
5803         case Tabular::M_ALIGN_RIGHT:
5804         case Tabular::ALIGN_RIGHT:
5805                 setAlign = LYX_ALIGN_RIGHT;
5806                 break;
5807
5808         case Tabular::M_ALIGN_CENTER:
5809         case Tabular::ALIGN_CENTER:
5810                 setAlign = LYX_ALIGN_CENTER;
5811                 break;
5812
5813         case Tabular::ALIGN_BLOCK:
5814                 setAlign = LYX_ALIGN_BLOCK;
5815                 break;
5816
5817         case Tabular::ALIGN_DECIMAL:
5818                 setAlign = LYX_ALIGN_DECIMAL;
5819                 break;
5820
5821         case Tabular::M_VALIGN_TOP:
5822         case Tabular::VALIGN_TOP:
5823                 setVAlign = Tabular::LYX_VALIGN_TOP;
5824                 break;
5825
5826         case Tabular::M_VALIGN_BOTTOM:
5827         case Tabular::VALIGN_BOTTOM:
5828                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
5829                 break;
5830
5831         case Tabular::M_VALIGN_MIDDLE:
5832         case Tabular::VALIGN_MIDDLE:
5833                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
5834                 break;
5835
5836         default:
5837                 break;
5838         }
5839
5840         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5841         row_type const row = tabular.cellRow(cur.idx());
5842         col_type const column = tabular.cellColumn(cur.idx());
5843         bool flag = true;
5844         Tabular::ltType ltt;
5845
5846         switch (feature) {
5847
5848         case Tabular::SET_TABULAR_WIDTH:
5849                 tabular.setTabularWidth(Length(value));
5850                 break;
5851
5852         case Tabular::SET_PWIDTH: {
5853                 Length const len(value);
5854                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5855                         tabular.setColumnPWidth(cur, tabular.cellIndex(row, c), len);
5856                         if (len.zero()
5857                             && tabular.getAlignment(tabular.cellIndex(row, c), true) == LYX_ALIGN_BLOCK)
5858                                 tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
5859                 }
5860                 break;
5861         }
5862
5863         case Tabular::SET_MPWIDTH:
5864                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
5865                 break;
5866
5867         case Tabular::TOGGLE_VARWIDTH_COLUMN: {
5868                 bool const varwidth = value == "on";
5869                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5870                         tabular.toggleVarwidth(tabular.cellIndex(row, c), varwidth);
5871                 break;
5872         }
5873
5874         case Tabular::SET_MROFFSET:
5875                 tabular.setMROffset(cur, cur.idx(), Length(value));
5876                 break;
5877
5878         case Tabular::SET_SPECIAL_COLUMN:
5879         case Tabular::SET_SPECIAL_MULTICOLUMN:
5880                 if (value == "none")
5881                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
5882                 else
5883                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
5884                 break;
5885
5886         case Tabular::APPEND_ROW:
5887                 // append the row into the tabular
5888                 tabular.appendRow(row);
5889                 break;
5890
5891         case Tabular::APPEND_COLUMN:
5892                 // append the column into the tabular
5893                 tabular.appendColumn(column);
5894                 cur.idx() = tabular.cellIndex(row, column);
5895                 break;
5896
5897         case Tabular::DELETE_ROW:
5898                 if (sel_row_end == tabular.nrows() - 1 && sel_row_start != 0) {
5899                         for (col_type c = 0; c < tabular.ncols(); c++)
5900                                 tabular.setBottomLine(tabular.cellIndex(sel_row_start - 1, c),
5901                                         tabular.bottomLine(tabular.cellIndex(sel_row_end, c)));
5902                 }
5903
5904                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5905                         tabular.deleteRow(sel_row_start);
5906                 if (sel_row_start >= tabular.nrows())
5907                         --sel_row_start;
5908                 cur.idx() = tabular.cellIndex(sel_row_start, column);
5909                 cur.pit() = 0;
5910                 cur.pos() = 0;
5911                 cur.selection(false);
5912                 break;
5913
5914         case Tabular::DELETE_COLUMN:
5915                 if (sel_col_end == tabular.ncols() - 1 && sel_col_start != 0) {
5916                         for (row_type r = 0; r < tabular.nrows(); r++)
5917                                 tabular.setRightLine(tabular.cellIndex(r, sel_col_start - 1),
5918                                         tabular.rightLine(tabular.cellIndex(r, sel_col_end)));
5919                 }
5920
5921                 if (sel_col_start == 0 && sel_col_end != tabular.ncols() - 1) {
5922                         for (row_type r = 0; r < tabular.nrows(); r++)
5923                                 tabular.setLeftLine(tabular.cellIndex(r, sel_col_end + 1),
5924                                         tabular.leftLine(tabular.cellIndex(r, 0)));
5925                 }
5926
5927                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5928                         tabular.deleteColumn(sel_col_start);
5929                 if (sel_col_start >= tabular.ncols())
5930                         --sel_col_start;
5931                 cur.idx() = tabular.cellIndex(row, sel_col_start);
5932                 cur.pit() = 0;
5933                 cur.pos() = 0;
5934                 cur.selection(false);
5935                 break;
5936
5937         case Tabular::COPY_ROW:
5938                 tabular.copyRow(row);
5939                 break;
5940
5941         case Tabular::COPY_COLUMN:
5942                 tabular.copyColumn(column);
5943                 cur.idx() = tabular.cellIndex(row, column);
5944                 break;
5945
5946         case Tabular::MOVE_COLUMN_RIGHT:
5947                 tabular.moveColumn(column, Tabular::RIGHT);
5948                 cur.idx() = tabular.cellIndex(row, column + 1);
5949                 break;
5950
5951         case Tabular::MOVE_COLUMN_LEFT:
5952                 tabular.moveColumn(column, Tabular::LEFT);
5953                 cur.idx() = tabular.cellIndex(row, column - 1);
5954                 break;
5955
5956         case Tabular::MOVE_ROW_DOWN:
5957                 tabular.moveRow(row, Tabular::DOWN);
5958                 cur.idx() = tabular.cellIndex(row + 1, column);
5959                 break;
5960
5961         case Tabular::MOVE_ROW_UP:
5962                 tabular.moveRow(row, Tabular::UP);
5963                 cur.idx() = tabular.cellIndex(row - 1, column);
5964                 break;
5965
5966         case Tabular::SET_LINE_TOP:
5967         case Tabular::TOGGLE_LINE_TOP: {
5968                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
5969                                ? (value == "true") : !tabular.topLine(cur.idx());
5970                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5971                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5972                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
5973                 break;
5974         }
5975
5976         case Tabular::SET_LINE_BOTTOM:
5977         case Tabular::TOGGLE_LINE_BOTTOM: {
5978                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
5979                                ? (value == "true") : !tabular.bottomLine(cur.idx());
5980                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5981                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5982                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
5983                 break;
5984         }
5985
5986         case Tabular::SET_LINE_LEFT:
5987         case Tabular::TOGGLE_LINE_LEFT: {
5988                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
5989                                ? (value == "true") : !tabular.leftLine(cur.idx());
5990                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5991                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5992                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
5993                 break;
5994         }
5995
5996         case Tabular::SET_LINE_RIGHT:
5997         case Tabular::TOGGLE_LINE_RIGHT: {
5998                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
5999                                ? (value == "true") : !tabular.rightLine(cur.idx());
6000                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6001                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6002                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
6003                 break;
6004         }
6005
6006         case Tabular::M_ALIGN_LEFT:
6007         case Tabular::M_ALIGN_RIGHT:
6008         case Tabular::M_ALIGN_CENTER:
6009         case Tabular::ALIGN_LEFT:
6010         case Tabular::ALIGN_RIGHT:
6011         case Tabular::ALIGN_CENTER:
6012         case Tabular::ALIGN_BLOCK:
6013         case Tabular::ALIGN_DECIMAL:
6014                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6015                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6016                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign,
6017                                 !tabular.getPWidth(c).zero());
6018                 break;
6019
6020         case Tabular::M_VALIGN_TOP:
6021         case Tabular::M_VALIGN_BOTTOM:
6022         case Tabular::M_VALIGN_MIDDLE:
6023                 flag = false;
6024                 // fall through
6025         case Tabular::VALIGN_TOP:
6026         case Tabular::VALIGN_BOTTOM:
6027         case Tabular::VALIGN_MIDDLE:
6028                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6029                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6030                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
6031                 break;
6032
6033         case Tabular::SET_MULTICOLUMN: {
6034                 if (!cur.selection()) {
6035                         // just multicol for one single cell
6036                         // check whether we are completely in a multicol
6037                         if (!tabular.isMultiColumn(cur.idx()))
6038                                 tabular.setMultiColumn(cur, cur.idx(), 1,
6039                                         tabular.rightLine(cur.idx()));
6040                         break;
6041                 }
6042                 // we have a selection so this means we just add all these
6043                 // cells to form a multicolumn cell
6044                 idx_type const s_start = cur.selBegin().idx();
6045                 row_type const col_start = tabular.cellColumn(s_start);
6046                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
6047                 cur.idx() = tabular.setMultiColumn(cur, s_start, col_end - col_start + 1,
6048                                                    tabular.rightLine(cur.selEnd().idx()));
6049                 cur.pit() = 0;
6050                 cur.pos() = 0;
6051                 cur.selection(false);
6052                 break;
6053         }
6054
6055         case Tabular::UNSET_MULTICOLUMN: {
6056                 if (!cur.selection()) {
6057                         if (tabular.isMultiColumn(cur.idx()))
6058                                 tabular.unsetMultiColumn(cur.idx());
6059                 }
6060                 break;
6061         }
6062
6063         case Tabular::MULTICOLUMN: {
6064                 if (!cur.selection()) {
6065                         if (tabular.isMultiColumn(cur.idx()))
6066                                 tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
6067                         else
6068                                 tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
6069                         break;
6070                 }
6071                 bool merge = false;
6072                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
6073                         row_type const r = sel_row_start;
6074                         if (!tabular.isMultiColumn(tabular.cellIndex(r, c))
6075                             || (r > sel_row_start && !tabular.isPartOfMultiColumn(r, c)))
6076                                 merge = true;
6077                 }
6078                 // If the selection contains at least one singlecol cell
6079                 // or multiple multicol cells,
6080                 // we assume the user will merge is to a single multicol
6081                 if (merge)
6082                         tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
6083                 else
6084                         tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
6085                 break;
6086         }
6087
6088         case Tabular::SET_MULTIROW: {
6089                 if (!cur.selection()) {
6090                         // just multirow for one single cell
6091                         // check whether we are completely in a multirow
6092                         if (!tabular.isMultiRow(cur.idx()))
6093                                 tabular.setMultiRow(cur, cur.idx(), 1,
6094                                                     tabular.bottomLine(cur.idx()),
6095                                                     tabular.getAlignment(cur.idx()));
6096                         break;
6097                 }
6098                 // we have a selection so this means we just add all this
6099                 // cells to form a multirow cell
6100                 idx_type const s_start = cur.selBegin().idx();
6101                 row_type const row_start = tabular.cellRow(s_start);
6102                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
6103                 cur.idx() = tabular.setMultiRow(cur, s_start, row_end - row_start + 1,
6104                                                 tabular.bottomLine(cur.selEnd().idx()),
6105                                                 tabular.getAlignment(cur.selEnd().idx()));
6106                 cur.pit() = 0;
6107                 cur.pos() = 0;
6108                 cur.selection(false);
6109                 break;
6110         }
6111
6112         case Tabular::UNSET_MULTIROW: {
6113                 if (!cur.selection()) {
6114                         if (tabular.isMultiRow(cur.idx()))
6115                                 tabular.unsetMultiRow(cur.idx());
6116                 }
6117                 break;
6118         }
6119
6120         case Tabular::MULTIROW: {
6121                 if (!cur.selection()) {
6122                         if (tabular.isMultiRow(cur.idx()))
6123                                 tabularFeatures(cur, Tabular::UNSET_MULTIROW);
6124                         else
6125                                 tabularFeatures(cur, Tabular::SET_MULTIROW);
6126                         break;
6127                 }
6128                 bool merge = false;
6129                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6130                         col_type const c = sel_col_start;
6131                         if (!tabular.isMultiRow(tabular.cellIndex(r, c))
6132                             || (r > sel_row_start && !tabular.isPartOfMultiRow(r, c)))
6133                                 merge = true;
6134                 }
6135                 // If the selection contains at least one singlerow cell
6136                 // or multiple multirow cells,
6137                 // we assume the user will merge is to a single multirow
6138                 if (merge)
6139                         tabularFeatures(cur, Tabular::SET_MULTIROW);
6140                 else
6141                         tabularFeatures(cur, Tabular::UNSET_MULTIROW);
6142                 break;
6143         }
6144
6145         case Tabular::SET_INNER_LINES:
6146                 setLinesInnerOnly = true;
6147                 // fall through
6148         case Tabular::SET_ALL_LINES:
6149                 setLines = true;
6150                 // fall through
6151         case Tabular::UNSET_ALL_LINES:
6152                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6153                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
6154                                 idx_type const cell = tabular.cellIndex(r, c);
6155                                 if (!setLinesInnerOnly || r != sel_row_start)
6156                                         tabular.setTopLine(cell, setLines);
6157                                 if ((!setLinesInnerOnly || r != sel_row_end)
6158                                     && (!setLines || r == sel_row_end))
6159                                         tabular.setBottomLine(cell, setLines);
6160                                 if ((!setLinesInnerOnly || c != sel_col_end)
6161                                     && (!setLines || c == sel_col_end))
6162                                         tabular.setRightLine(cell, setLines);
6163                                 if ((!setLinesInnerOnly || c != sel_col_start))
6164                                         tabular.setLeftLine(cell, setLines);
6165                         }
6166                 break;
6167
6168         case Tabular::SET_BORDER_LINES:
6169                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6170                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
6171                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
6172                 }
6173                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
6174                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
6175                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
6176                 }
6177                 break;
6178
6179         case Tabular::TOGGLE_LONGTABULAR:
6180                 if (tabular.is_long_tabular)
6181                         tabularFeatures(cur, Tabular::UNSET_LONGTABULAR);
6182                 else
6183                         tabular.is_long_tabular = true;
6184                 break;
6185
6186         case Tabular::SET_LONGTABULAR:
6187                 tabular.is_long_tabular = true;
6188                 break;
6189
6190         case Tabular::UNSET_LONGTABULAR:
6191                 for (row_type r = 0; r < tabular.nrows(); ++r) {
6192                         if (tabular.ltCaption(r)) {
6193                                 cur.idx() = tabular.cellIndex(r, 0);
6194                                 cur.pit() = 0;
6195                                 cur.pos() = 0;
6196                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
6197                         }
6198                 }
6199                 tabular.is_long_tabular = false;
6200                 break;
6201
6202         case Tabular::SET_ROTATE_TABULAR:
6203                 tabular.rotate = convert<int>(value);
6204                 break;
6205
6206         case Tabular::UNSET_ROTATE_TABULAR:
6207                 tabular.rotate = 0;
6208                 break;
6209
6210         case Tabular::TOGGLE_ROTATE_TABULAR:
6211                 // when pressing the rotate button we default to 90° rotation
6212                 tabular.rotate != 0 ? tabular.rotate = 0 : tabular.rotate = 90;
6213                 break;
6214
6215         case Tabular::TABULAR_VALIGN_TOP:
6216                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
6217                 break;
6218
6219         case Tabular::TABULAR_VALIGN_MIDDLE:
6220                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
6221                 break;
6222
6223         case Tabular::TABULAR_VALIGN_BOTTOM:
6224                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
6225                 break;
6226
6227         case Tabular::LONGTABULAR_ALIGN_LEFT:
6228                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
6229                 break;
6230
6231         case Tabular::LONGTABULAR_ALIGN_CENTER:
6232                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
6233                 break;
6234
6235         case Tabular::LONGTABULAR_ALIGN_RIGHT:
6236                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
6237                 break;
6238
6239         case Tabular::SET_ROTATE_CELL:
6240                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6241                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6242                                 tabular.setRotateCell(tabular.cellIndex(r, c), convert<int>(value));
6243                 break;
6244
6245         case Tabular::UNSET_ROTATE_CELL:
6246                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6247                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6248                                 tabular.setRotateCell(tabular.cellIndex(r, c), 0);
6249                 break;
6250
6251         case Tabular::TOGGLE_ROTATE_CELL:
6252                 {
6253                 bool oneNotRotated = oneCellHasRotationState(false,
6254                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
6255
6256                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6257                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
6258                                 // when pressing the rotate cell button we default to 90° rotation
6259                                 if (oneNotRotated)
6260                                         tabular.setRotateCell(tabular.cellIndex(r, c), 90);
6261                                 else
6262                                         tabular.setRotateCell(tabular.cellIndex(r, c), 0);
6263                         }
6264                 }
6265                 break;
6266
6267         case Tabular::SET_USEBOX: {
6268                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
6269                 if (val == tabular.getUsebox(cur.idx()))
6270                         val = Tabular::BOX_NONE;
6271                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6272                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6273                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
6274                 break;
6275         }
6276
6277         case Tabular::UNSET_LTFIRSTHEAD:
6278                 flag = false;
6279                 // fall through
6280         case Tabular::SET_LTFIRSTHEAD:
6281                 tabular.getRowOfLTFirstHead(row, ltt);
6282                 checkLongtableSpecial(ltt, value, flag);
6283                 tabular.setLTHead(row, flag, ltt, true);
6284                 break;
6285
6286         case Tabular::UNSET_LTHEAD:
6287                 flag = false;
6288                 // fall through
6289         case Tabular::SET_LTHEAD:
6290                 tabular.getRowOfLTHead(row, ltt);
6291                 checkLongtableSpecial(ltt, value, flag);
6292                 tabular.setLTHead(row, flag, ltt, false);
6293                 break;
6294
6295         case Tabular::UNSET_LTFOOT:
6296                 flag = false;
6297                 // fall through
6298         case Tabular::SET_LTFOOT:
6299                 tabular.getRowOfLTFoot(row, ltt);
6300                 checkLongtableSpecial(ltt, value, flag);
6301                 tabular.setLTFoot(row, flag, ltt, false);
6302                 break;
6303
6304         case Tabular::UNSET_LTLASTFOOT:
6305                 flag = false;
6306                 // fall through
6307         case Tabular::SET_LTLASTFOOT:
6308                 tabular.getRowOfLTLastFoot(row, ltt);
6309                 checkLongtableSpecial(ltt, value, flag);
6310                 tabular.setLTFoot(row, flag, ltt, true);
6311                 break;
6312
6313         case Tabular::UNSET_LTNEWPAGE:
6314                 flag = false;
6315                 // fall through
6316         case Tabular::SET_LTNEWPAGE:
6317                 tabular.setLTNewPage(row, flag);
6318                 break;
6319
6320         case Tabular::SET_LTCAPTION: {
6321                 if (tabular.ltCaption(row))
6322                         break;
6323                 cur.idx() = tabular.setLTCaption(cur, row, true);
6324                 cur.pit() = 0;
6325                 cur.pos() = 0;
6326                 cur.selection(false);
6327                 // If a row is set as caption, then also insert
6328                 // a caption. Otherwise the LaTeX output is broken.
6329                 // Select cell if it is non-empty
6330                 if (cur.lastpos() > 0 || cur.lastpit() > 0)
6331                         lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
6332                 lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
6333                 break;
6334         }
6335
6336         case Tabular::UNSET_LTCAPTION: {
6337                 if (!tabular.ltCaption(row))
6338                         break;
6339                 cur.idx() = tabular.setLTCaption(cur, row, false);
6340                 cur.pit() = 0;
6341                 cur.pos() = 0;
6342                 cur.selection(false);
6343                 FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
6344                 if (lyx::getStatus(fr).enabled())
6345                         lyx::dispatch(fr);
6346                 break;
6347         }
6348
6349         case Tabular::TOGGLE_LTCAPTION: {
6350                 if (tabular.ltCaption(row))
6351                         tabularFeatures(cur, Tabular::UNSET_LTCAPTION);
6352                 else
6353                         tabularFeatures(cur, Tabular::SET_LTCAPTION);
6354                 break;
6355         }
6356
6357         case Tabular::TOGGLE_BOOKTABS:
6358                 tabular.use_booktabs = !tabular.use_booktabs;
6359                 break;
6360
6361         case Tabular::SET_BOOKTABS:
6362                 tabular.use_booktabs = true;
6363                 break;
6364
6365         case Tabular::UNSET_BOOKTABS:
6366                 tabular.use_booktabs = false;
6367                 break;
6368
6369         case Tabular::SET_TOP_SPACE: {
6370                 Length len;
6371                 if (value == "default")
6372                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6373                                 tabular.row_info[r].top_space_default = true;
6374                 else if (value == "none")
6375                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6376                                 tabular.row_info[r].top_space_default = false;
6377                                 tabular.row_info[r].top_space = len;
6378                         }
6379                 else if (isValidLength(value, &len))
6380                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6381                                 tabular.row_info[r].top_space_default = false;
6382                                 tabular.row_info[r].top_space = len;
6383                         }
6384                 break;
6385         }
6386
6387         case Tabular::SET_BOTTOM_SPACE: {
6388                 Length len;
6389                 if (value == "default")
6390                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6391                                 tabular.row_info[r].bottom_space_default = true;
6392                 else if (value == "none")
6393                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6394                                 tabular.row_info[r].bottom_space_default = false;
6395                                 tabular.row_info[r].bottom_space = len;
6396                         }
6397                 else if (isValidLength(value, &len))
6398                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6399                                 tabular.row_info[r].bottom_space_default = false;
6400                                 tabular.row_info[r].bottom_space = len;
6401                         }
6402                 break;
6403         }
6404
6405         case Tabular::SET_INTERLINE_SPACE: {
6406                 Length len;
6407                 if (value == "default")
6408                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6409                                 tabular.row_info[r].interline_space_default = true;
6410                 else if (value == "none")
6411                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6412                                 tabular.row_info[r].interline_space_default = false;
6413                                 tabular.row_info[r].interline_space = len;
6414                         }
6415                 else if (isValidLength(value, &len))
6416                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6417                                 tabular.row_info[r].interline_space_default = false;
6418                                 tabular.row_info[r].interline_space = len;
6419                         }
6420                 break;
6421         }
6422
6423         case Tabular::SET_DECIMAL_POINT:
6424                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6425                         tabular.column_info[c].decimal_point = from_utf8(value);
6426                 break;
6427
6428         // dummy stuff just to avoid warnings
6429         case Tabular::LAST_ACTION:
6430                 break;
6431         }
6432 }
6433
6434
6435 bool InsetTabular::copySelection(Cursor & cur)
6436 {
6437         if (!cur.selection())
6438                 return false;
6439
6440         row_type rs, re;
6441         col_type cs, ce;
6442         getSelection(cur, rs, re, cs, ce);
6443
6444         paste_tabular.reset(new Tabular(tabular));
6445
6446         for (row_type r = 0; r < rs; ++r)
6447                 paste_tabular->deleteRow(0);
6448
6449         row_type const rows = re - rs + 1;
6450         while (paste_tabular->nrows() > rows)
6451                 paste_tabular->deleteRow(rows);
6452
6453         for (col_type c = 0; c < cs; ++c)
6454                 paste_tabular->deleteColumn(0);
6455
6456         col_type const columns = ce - cs + 1;
6457         while (paste_tabular->ncols() > columns)
6458                 paste_tabular->deleteColumn(columns);
6459
6460         paste_tabular->setBuffer(tabular.buffer());
6461
6462         odocstringstream os;
6463         OutputParams const runparams(0);
6464         paste_tabular->plaintext(os, runparams, 0, true, '\t', INT_MAX);
6465         // Needed for the "Edit->Paste recent" menu and the system clipboard.
6466         cap::copySelection(cur, os.str());
6467
6468         // mark tabular stack dirty
6469         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
6470         // when we (hopefully) have a one-for-all paste mechanism.
6471         // This must be called after cap::copySelection.
6472         dirtyTabularStack(true);
6473
6474         return true;
6475 }
6476
6477
6478 bool InsetTabular::pasteClipboard(Cursor & cur)
6479 {
6480         if (!paste_tabular)
6481                 return false;
6482         col_type actcol = tabular.cellColumn(cur.idx());
6483         row_type actrow = tabular.cellRow(cur.idx());
6484
6485         if (cur.selIsMultiCell()) {
6486                 row_type re;
6487                 col_type ce;
6488                 getSelection(cur, actrow, re, actcol, ce);
6489         }
6490
6491         for (row_type r1 = 0, r2 = actrow;
6492              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
6493              ++r1, ++r2) {
6494                 for (col_type c1 = 0, c2 = actcol;
6495                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
6496                     ++c1, ++c2) {
6497                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
6498                               tabular.isPartOfMultiColumn(r2, c2))
6499                                 continue;
6500                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
6501                                 --c2;
6502                                 continue;
6503                         }
6504                         if (tabular.isPartOfMultiColumn(r2, c2)) {
6505                                 --c1;
6506                                 continue;
6507                         }
6508                         shared_ptr<InsetTableCell> inset(
6509                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
6510                         tabular.setCellInset(r2, c2, inset);
6511                         // FIXME?: why do we need to do this explicitly? (EL)
6512                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
6513
6514                         // FIXME: change tracking (MG)
6515                         inset->setChange(Change(buffer().params().track_changes ?
6516                                                 Change::INSERTED : Change::UNCHANGED));
6517                         cur.pos() = 0;
6518                         cur.pit() = 0;
6519                 }
6520         }
6521         return true;
6522 }
6523
6524
6525 void InsetTabular::cutSelection(Cursor & cur)
6526 {
6527         if (!cur.selection())
6528                 return;
6529
6530         row_type rs, re;
6531         col_type cs, ce;
6532         getSelection(cur, rs, re, cs, ce);
6533         for (row_type r = rs; r <= re; ++r) {
6534                 for (col_type c = cs; c <= ce; ++c) {
6535                         shared_ptr<InsetTableCell> t
6536                                 = cell(tabular.cellIndex(r, c));
6537                         if (buffer().params().track_changes)
6538                                 // FIXME: Change tracking (MG)
6539                                 t->setChange(Change(Change::DELETED));
6540                         else
6541                                 t->clear();
6542                 }
6543         }
6544
6545         // cursor position might be invalid now
6546         if (cur.pit() > cur.lastpit())
6547                 cur.pit() = cur.lastpit();
6548         if (cur.pos() > cur.lastpos())
6549                 cur.pos() = cur.lastpos();
6550         cur.clearSelection();
6551 }
6552
6553
6554 bool InsetTabular::isRightToLeft(Cursor & cur) const
6555 {
6556         // LASSERT: It might be better to abandon this Buffer.
6557         LASSERT(cur.depth() > 1, return false);
6558         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
6559         pos_type const parentpos = cur[cur.depth() - 2].pos();
6560         return parentpar.getFontSettings(buffer().params(),
6561                                          parentpos).language()->rightToLeft();
6562 }
6563
6564
6565 docstring InsetTabular::asString(idx_type stidx, idx_type enidx,
6566                                  bool intoInsets)
6567 {
6568         LASSERT(stidx <= enidx, return docstring());
6569         docstring retval;
6570         col_type const col1 = tabular.cellColumn(stidx);
6571         col_type const col2 = tabular.cellColumn(enidx);
6572         row_type const row1 = tabular.cellRow(stidx);
6573         row_type const row2 = tabular.cellRow(enidx);
6574         bool first = true;
6575         for (col_type col = col1; col <= col2; col++)
6576                 for (row_type row = row1; row <= row2; row++) {
6577                         if (!first)
6578                                 retval += "\n";
6579                         else
6580                                 first = false;
6581                         retval += tabular.cellInset(row, col)->asString(intoInsets);
6582                 }
6583         return retval;
6584 }
6585
6586
6587 void InsetTabular::getSelection(Cursor & cur,
6588         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
6589 {
6590         CursorSlice const & beg = cur.selBegin();
6591         CursorSlice const & end = cur.selEnd();
6592         cs = tabular.cellColumn(beg.idx());
6593         ce = tabular.cellColumn(end.idx());
6594         if (cs > ce)
6595                 swap(cs, ce);
6596
6597         rs = tabular.cellRow(beg.idx());
6598         re = tabular.cellRow(end.idx());
6599         if (rs > re)
6600                 swap(rs, re);
6601 }
6602
6603
6604 Text * InsetTabular::getText(int idx) const
6605 {
6606         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
6607 }
6608
6609
6610 void InsetTabular::setChange(Change const & change)
6611 {
6612         for (idx_type idx = 0; idx < nargs(); ++idx)
6613                 cell(idx)->setChange(change);
6614 }
6615
6616
6617 void InsetTabular::acceptChanges()
6618 {
6619         for (idx_type idx = 0; idx < nargs(); ++idx)
6620                 cell(idx)->acceptChanges();
6621 }
6622
6623
6624 void InsetTabular::rejectChanges()
6625 {
6626         for (idx_type idx = 0; idx < nargs(); ++idx)
6627                 cell(idx)->rejectChanges();
6628 }
6629
6630
6631 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
6632 {
6633         return tabular.getPWidth(cell).zero();
6634 }
6635
6636
6637 bool InsetTabular::forcePlainLayout(idx_type cell) const
6638 {
6639         return tabular.isMultiColumn(cell) && !tabular.getPWidth(cell).zero();
6640 }
6641
6642
6643 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
6644                                      bool usePaste)
6645 {
6646         if (buf.length() <= 0)
6647                 return true;
6648
6649         col_type cols = 1;
6650         row_type rows = 1;
6651         col_type maxCols = 1;
6652         size_t const len = buf.length();
6653         size_t p = 0;
6654
6655         while (p < len &&
6656                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
6657                 switch (buf[p]) {
6658                 case '\t':
6659                         ++cols;
6660                         break;
6661                 case '\n':
6662                         if (p + 1 < len)
6663                                 ++rows;
6664                         maxCols = max(cols, maxCols);
6665                         cols = 1;
6666                         break;
6667                 }
6668                 ++p;
6669         }
6670         maxCols = max(cols, maxCols);
6671         Tabular * loctab;
6672         idx_type cell = 0;
6673         col_type ocol = 0;
6674         row_type row = 0;
6675         if (usePaste) {
6676                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
6677                 loctab = paste_tabular.get();
6678                 dirtyTabularStack(true);
6679         } else {
6680                 loctab = &tabular;
6681                 cell = bv.cursor().idx();
6682                 ocol = tabular.cellColumn(cell);
6683                 row = tabular.cellRow(cell);
6684         }
6685
6686         size_t op = 0;
6687         idx_type const cells = loctab->numberofcells;
6688         p = 0;
6689         cols = ocol;
6690         rows = loctab->nrows();
6691         col_type const columns = loctab->ncols();
6692
6693         while (cell < cells && p < len && row < rows &&
6694                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
6695         {
6696                 if (p >= len)
6697                         break;
6698                 switch (buf[p]) {
6699                 case '\t':
6700                         // we can only set this if we are not too far right
6701                         if (cols < columns) {
6702                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6703                                 Font const font = bv.textMetrics(&inset->text()).
6704                                         displayFont(0, 0);
6705                                 inset->setText(buf.substr(op, p - op), font,
6706                                                buffer().params().track_changes);
6707                                 ++cols;
6708                                 ++cell;
6709                         }
6710                         break;
6711                 case '\n':
6712                         // we can only set this if we are not too far right
6713                         if (cols < columns) {
6714                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
6715                                 Font const font = bv.textMetrics(&inset->text()).
6716                                         displayFont(0, 0);
6717                                 inset->setText(buf.substr(op, p - op), font,
6718                                                buffer().params().track_changes);
6719                         }
6720                         cols = ocol;
6721                         ++row;
6722                         if (row < rows)
6723                                 cell = loctab->cellIndex(row, cols);
6724                         break;
6725                 }
6726                 ++p;
6727                 op = p;
6728         }
6729         // check for the last cell if there is no trailing '\n'
6730         if (cell < cells && op < len) {
6731                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6732                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
6733                 inset->setText(buf.substr(op, len - op), font,
6734                         buffer().params().track_changes);
6735         }
6736         return true;
6737 }
6738
6739
6740 void InsetTabular::addPreview(DocIterator const & inset_pos,
6741         PreviewLoader & loader) const
6742 {
6743         DocIterator cell_pos = inset_pos;
6744
6745         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
6746         for (row_type r = 0; r < tabular.nrows(); ++r) {
6747                 for (col_type c = 0; c < tabular.ncols(); ++c) {
6748                         cell_pos.top().idx() = tabular.cellIndex(r, c);
6749                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
6750                 }
6751         }
6752 }
6753
6754
6755 bool InsetTabular::completionSupported(Cursor const & cur) const
6756 {
6757         Cursor const & bvCur = cur.bv().cursor();
6758         if (&bvCur.inset() != this)
6759                 return false;
6760         return cur.text()->completionSupported(cur);
6761 }
6762
6763
6764 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
6765 {
6766         return completionSupported(cur);
6767 }
6768
6769
6770 bool InsetTabular::automaticInlineCompletion() const
6771 {
6772         return lyxrc.completion_inline_text;
6773 }
6774
6775
6776 bool InsetTabular::automaticPopupCompletion() const
6777 {
6778         return lyxrc.completion_popup_text;
6779 }
6780
6781
6782 bool InsetTabular::showCompletionCursor() const
6783 {
6784         return lyxrc.completion_cursor_text;
6785 }
6786
6787
6788 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
6789 {
6790         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
6791 }
6792
6793
6794 docstring InsetTabular::completionPrefix(Cursor const & cur) const
6795 {
6796         if (!completionSupported(cur))
6797                 return docstring();
6798         return cur.text()->completionPrefix(cur);
6799 }
6800
6801
6802 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
6803 {
6804         if (!completionSupported(cur))
6805                 return false;
6806
6807         return cur.text()->insertCompletion(cur, s, finished);
6808 }
6809
6810
6811 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y,
6812                                     Dimension & dim) const
6813 {
6814         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
6815         tm.completionPosAndDim(cur, x, y, dim);
6816 }
6817
6818
6819 void InsetTabular::string2params(string const & in, InsetTabular & inset)
6820 {
6821         istringstream data(in);
6822         Lexer lex;
6823         lex.setStream(data);
6824
6825         if (in.empty())
6826                 return;
6827
6828         string token;
6829         lex >> token;
6830         if (!lex || token != "tabular") {
6831                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
6832                 return;
6833         }
6834
6835         // This is part of the inset proper that is usually swallowed
6836         // by Buffer::readInset
6837         lex >> token;
6838         if (!lex || token != "Tabular") {
6839                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
6840                 return;
6841         }
6842
6843         inset.read(lex);
6844 }
6845
6846
6847 string InsetTabular::params2string(InsetTabular const & inset)
6848 {
6849         ostringstream data;
6850         data << "tabular" << ' ';
6851         inset.write(data);
6852         data << "\\end_inset\n";
6853         return data.str();
6854 }
6855
6856
6857 void InsetTabular::setLayoutForHiddenCells(DocumentClass const & dc)
6858 {
6859         for (Tabular::col_type c = 0; c < tabular.ncols(); ++c) {
6860                 for (Tabular::row_type r = 0; r < tabular.nrows(); ++r) {
6861                         if (!tabular.isPartOfMultiColumn(r,c) &&
6862                             !tabular.isPartOfMultiRow(r,c))
6863                                 continue;
6864
6865                         ParagraphList & parlist = tabular.cellInset(r,c)->paragraphs();
6866                         ParagraphList::iterator it = parlist.begin();
6867                         ParagraphList::iterator const en = parlist.end();
6868                         for (; it != en; ++it)
6869                                         it->setLayout(dc.plainLayout());
6870                 }
6871         }
6872 }
6873
6874
6875 } // namespace lyx